Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion internal/httputil/response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import "net/http"
// interfaces (e.g. http.Flusher, http.Hijacker) on the underlying writer.
//
// Embed BaseResponseWriter in package-specific types to avoid duplicating
// this status-capture boilerplate.
// this status-capture boilerplate. Package-specific wrappers can then add
// their own concerns, such as server response body buffering or tracing-only
// status capture, while reusing the same net/http-compatible behavior.
type BaseResponseWriter struct {
http.ResponseWriter
// StatusCode holds the captured HTTP status code. It is set by WriteHeader
Expand Down
5 changes: 3 additions & 2 deletions internal/server/response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import (
var logResponseWriter = logger.ForFile()

// responseWriter wraps http.ResponseWriter to capture response body and status code.
// It embeds httputil.BaseResponseWriter for shared status-code capture logic, and
// adds body buffering for debug logging.
// It embeds httputil.BaseResponseWriter for shared status-code capture logic and
// optional-interface passthrough via Unwrap, and adds body buffering for debug
// logging.
type responseWriter struct {
httputil.BaseResponseWriter
body bytes.Buffer
Expand Down
24 changes: 24 additions & 0 deletions internal/server/response_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ import (
"github.com/stretchr/testify/require"
)

type mockFlusher struct {
*httptest.ResponseRecorder
flushed bool
}

func (m *mockFlusher) Flush() { m.flushed = true }

func TestNewResponseWriter(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -76,6 +83,7 @@ func TestResponseWriter_WriteImplicitStatus200(t *testing.T) {
require.NoError(t, err)

// net/http sets status 200 on first Write if WriteHeader wasn't called
assert.Equal(t, http.StatusOK, w.StatusCode)
assert.Equal(t, http.StatusOK, rr.Code)
}

Expand Down Expand Up @@ -127,3 +135,19 @@ func TestResponseWriter_HeaderPassthrough(t *testing.T) {

assert.Equal(t, "application/json", rr.Header().Get("Content-Type"))
}

func TestResponseWriter_UnwrapExposesOptionalInterfaces(t *testing.T) {
t.Parallel()

rr := &mockFlusher{ResponseRecorder: httptest.NewRecorder()}
w := newResponseWriter(rr)

_, err := w.Write([]byte("content"))
require.NoError(t, err)

rc := http.NewResponseController(w)
err = rc.Flush()
require.NoError(t, err)
assert.True(t, rr.flushed)
assert.Equal(t, []byte("content"), w.Body())
}
Loading