From 03464794536c7254c09f2e81477f6608d9427abc Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Fri, 20 Nov 2026 07:32:30 -0800 Subject: [PATCH 1/4] fix: commit response on Flush, pass through 1xx, and clear stale error headers Response.Flush now commits an uncommitted response through WriteHeader, so Before hooks run, Committed is accurate, and the error handler no longer writes a body after the headers were already sent. Response.WriteHeader forwards informational status codes (1xx except 101) without committing the response, so a handler can send 103 Early Hints and still set its final status. DefaultHTTPErrorHandler removes Content-Length before writing its body, and removes Content-Encoding when no middleware wraps the response. Fixes #3240 Fixes #3241 Fixes #3242 Co-Authored-By: Claude Opus 5.5 --- echo.go | 8 +++++ echo_test.go | 41 +++++++++++++++++++++++++ response.go | 12 ++++++++ response_test.go | 79 ++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 140 insertions(+) diff --git a/echo.go b/echo.go index 7c8541d2a..f63ed9fbf 100644 --- a/echo.go +++ b/echo.go @@ -498,6 +498,14 @@ func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler { result = msg } + // Headers set for the failed response do not describe the error body. + h := c.Response().Header() + h.Del(HeaderContentLength) + if _, ok := c.response.(*Response); ok { + // A wrapping middleware may encode the error body itself, so only clear the coding without one. + h.Del(HeaderContentEncoding) + } + var cErr error if c.Request().Method == http.MethodHead { // Issue #608 cErr = c.NoContent(code) diff --git a/echo_test.go b/echo_test.go index dda5be7ca..2dcf4a2a5 100644 --- a/echo_test.go +++ b/echo_test.go @@ -1452,6 +1452,47 @@ func TestDefaultHTTPErrorHandler(t *testing.T) { } } +func TestDefaultHTTPErrorHandler_ClearsBodyHeaders(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + c.Response().Header().Set(HeaderContentEncoding, "br") + c.Response().Header().Set(HeaderContentLength, "5000") + return ErrNotFound + }) + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + + assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Empty(t, rec.Header().Get(HeaderContentEncoding)) + assert.Empty(t, rec.Header().Get(HeaderContentLength)) + assert.JSONEq(t, `{"message":"Not Found"}`, rec.Body.String()) +} + +type encodingResponseWriter struct { + http.ResponseWriter +} + +func (w *encodingResponseWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +func TestDefaultHTTPErrorHandler_KeepsEncodingOfWrappedResponse(t *testing.T) { + e := New() + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + c := e.NewContext(req, rec) + c.SetResponse(&encodingResponseWriter{ResponseWriter: c.Response()}) + c.Response().Header().Set(HeaderContentEncoding, "gzip") + c.Response().Header().Set(HeaderContentLength, "5000") + + DefaultHTTPErrorHandler(false)(c, ErrNotFound) + + assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Equal(t, "gzip", rec.Header().Get(HeaderContentEncoding)) + assert.Empty(t, rec.Header().Get(HeaderContentLength)) +} + func TestDefaultHTTPErrorHandler_CommitedResponse(t *testing.T) { e := New() req := httptest.NewRequest(http.MethodGet, "/", nil) diff --git a/response.go b/response.go index e218ef4d6..26697eaa6 100644 --- a/response.go +++ b/response.go @@ -52,6 +52,11 @@ func (r *Response) WriteHeader(code int) { r.logger.Error("echo: response already written to client") return } + if code >= 100 && code < 200 && code != http.StatusSwitchingProtocols { + // Informational responses precede the final status and do not commit the response. + r.ResponseWriter.WriteHeader(code) + return + } r.Status = code for _, fn := range r.beforeFuncs { fn() @@ -80,6 +85,13 @@ func (r *Response) Write(b []byte) (n int, err error) { // buffered data to the client. // See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) func (r *Response) Flush() { + if !r.Committed { + // Flushing sends the headers, so commit them the same way Write does. + if r.Status == 0 { + r.Status = http.StatusOK + } + r.WriteHeader(r.Status) + } err := http.NewResponseController(r.ResponseWriter).Flush() if err != nil && errors.Is(err, http.ErrNotSupported) { panic(fmt.Errorf("echo: response writer %T does not support flushing (http.Flusher interface)", r.ResponseWriter)) diff --git a/response_test.go b/response_test.go index 4ad849c04..24fde4000 100644 --- a/response_test.go +++ b/response_test.go @@ -4,12 +4,17 @@ package echo import ( + "context" "fmt" + "io" "net/http" "net/http/httptest" + "net/http/httptrace" + "net/textproto" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestResponse(t *testing.T) { @@ -421,3 +426,77 @@ func TestWrapHeadHandler_RouteLevelMiddlewareSeesTrueCommitted(t *testing.T) { assert.NoError(t, wrapped(c)) assert.True(t, committedAfterHandler) } + +func TestResponse_Flush_CommitsResponse(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + res := NewResponse(rec, e.Logger) + beforeCalled := false + res.Before(func() { + beforeCalled = true + res.Header().Set("X-Before", "1") + }) + + res.Flush() + + assert.True(t, res.Committed) + assert.True(t, beforeCalled) + assert.Equal(t, http.StatusOK, res.Status) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "1", rec.Header().Get("X-Before")) + assert.True(t, rec.Flushed) +} + +func TestResponse_Flush_ErrorHandlerSkipsCommittedResponse(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + if err := http.NewResponseController(c.Response()).Flush(); err != nil { + return err + } + return ErrBadRequest + }) + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + + assert.Equal(t, http.StatusOK, rec.Code) + assert.Empty(t, rec.Body.String()) +} + +func TestResponse_WriteHeader_Informational(t *testing.T) { + e := New() + srv := httptest.NewServer(e) + defer srv.Close() + + var status int + e.GET("/", func(c *Context) error { + c.Response().Header().Set("Link", "; rel=preload; as=style") + c.Response().WriteHeader(http.StatusEarlyHints) + r, err := UnwrapResponse(c.Response()) + require.NoError(t, err) + assert.False(t, r.Committed) + err = c.String(http.StatusCreated, "ok") + status = r.Status + return err + }) + + var informational []int + trace := &httptrace.ClientTrace{ + Got1xxResponse: func(code int, _ textproto.MIMEHeader) error { + informational = append(informational, code) + return nil + }, + } + req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + res, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + + assert.Equal(t, []int{http.StatusEarlyHints}, informational) + assert.Equal(t, http.StatusCreated, res.StatusCode) + assert.Equal(t, "ok", string(body)) + assert.Equal(t, http.StatusCreated, status) +} From c7d9bec906bd7cc7cb2dc8765497b0189de74f50 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Fri, 20 Nov 2026 07:37:05 -0800 Subject: [PATCH 2/4] fix: cover wrapped writers, both error handlers, and failed flushes - Both DefaultHTTPErrorHandler and ProblemDetailsHTTPErrorHandler now clear the headers that described the failed response (Content-Encoding, Content-Length, Content-Type, Content-Disposition, Content-Range, ETag, Last-Modified), whatever wraps the writer. - Response.Flush panics before committing when the writer cannot flush, so Recover can still send a 500. - headResponseWriter, delayedStatusWriter and the Gzip writer forward 1xx codes instead of treating them as the final status. - delayedStatusWriter.Flush sends its delayed status before flushing. Co-Authored-By: Claude Opus 5.5 --- echo.go | 25 ++++++++++++----- echo_test.go | 53 +++++++++++++++++++++++++----------- middleware/compress.go | 14 +++++----- middleware/compress_test.go | 38 ++++++++++++++++++++++++++ response.go | 42 ++++++++++++++++++++++++++++- response_test.go | 54 +++++++++++++++++++++++++++++++++++-- rfc9457.go | 1 + 7 files changed, 193 insertions(+), 34 deletions(-) diff --git a/echo.go b/echo.go index f63ed9fbf..762493a3b 100644 --- a/echo.go +++ b/echo.go @@ -460,6 +460,23 @@ func (e *Echo) Router() Router { // When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from // handler. Then the error that global error handler received will be ignored because we have already "committed" the // response and status code header has been sent to the client. +// clearRepresentationHeaders removes headers that described the response the +// handler meant to send, so they are not applied to the error body that replaces it. +// A middleware that encodes the error body sets its own Content-Encoding. +func clearRepresentationHeaders(h http.Header) { + for _, name := range []string{ + HeaderContentEncoding, + HeaderContentLength, + HeaderContentType, + HeaderContentDisposition, + "Content-Range", + "ETag", + HeaderLastModified, + } { + h.Del(name) + } +} + func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler { return func(c *Context, err error) { if r, _ := UnwrapResponse(c.response); r != nil && r.Committed { @@ -498,13 +515,7 @@ func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler { result = msg } - // Headers set for the failed response do not describe the error body. - h := c.Response().Header() - h.Del(HeaderContentLength) - if _, ok := c.response.(*Response); ok { - // A wrapping middleware may encode the error body itself, so only clear the coding without one. - h.Del(HeaderContentEncoding) - } + clearRepresentationHeaders(c.Response().Header()) var cErr error if c.Request().Method == http.MethodHead { // Issue #608 diff --git a/echo_test.go b/echo_test.go index 2dcf4a2a5..c52a34a7c 100644 --- a/echo_test.go +++ b/echo_test.go @@ -1452,21 +1452,42 @@ func TestDefaultHTTPErrorHandler(t *testing.T) { } } -func TestDefaultHTTPErrorHandler_ClearsBodyHeaders(t *testing.T) { - e := New() - e.GET("/", func(c *Context) error { - c.Response().Header().Set(HeaderContentEncoding, "br") - c.Response().Header().Set(HeaderContentLength, "5000") - return ErrNotFound - }) - req := httptest.NewRequest(http.MethodGet, "/", nil) - rec := httptest.NewRecorder() - e.ServeHTTP(rec, req) +func TestHTTPErrorHandlers_ClearRepresentationHeaders(t *testing.T) { + handlers := map[string]struct { + handler HTTPErrorHandler + contentType string + }{ + "default": {DefaultHTTPErrorHandler(false), MIMEApplicationJSON}, + "problem details": {ProblemDetailsHTTPErrorHandler(false), MIMEApplicationProblemJSON}, + } + for name, tt := range handlers { + t.Run(name, func(t *testing.T) { + e := New() + e.HTTPErrorHandler = tt.handler + e.GET("/", func(c *Context) error { + h := c.Response().Header() + h.Set(HeaderContentEncoding, "br") + h.Set(HeaderContentLength, "5000") + h.Set(HeaderContentType, "text/csv") + h.Set(HeaderContentDisposition, `attachment; filename="report.csv"`) + h.Set("Content-Range", "bytes 0-99/5000") + h.Set("ETag", `"v1"`) + h.Set(HeaderLastModified, "Wed, 21 Oct 2015 07:28:00 GMT") + h.Set("X-Request-Id", "keep") + return ErrNotFound + }) + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) - assert.Equal(t, http.StatusNotFound, rec.Code) - assert.Empty(t, rec.Header().Get(HeaderContentEncoding)) - assert.Empty(t, rec.Header().Get(HeaderContentLength)) - assert.JSONEq(t, `{"message":"Not Found"}`, rec.Body.String()) + assert.Equal(t, http.StatusNotFound, rec.Code) + for _, name := range []string{HeaderContentEncoding, HeaderContentLength, HeaderContentDisposition, "Content-Range", "ETag", HeaderLastModified} { + assert.Empty(t, rec.Header().Get(name), name) + } + assert.Equal(t, tt.contentType, rec.Header().Get(HeaderContentType)) + assert.Equal(t, "keep", rec.Header().Get("X-Request-Id")) + }) + } } type encodingResponseWriter struct { @@ -1477,7 +1498,7 @@ func (w *encodingResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } -func TestDefaultHTTPErrorHandler_KeepsEncodingOfWrappedResponse(t *testing.T) { +func TestDefaultHTTPErrorHandler_ClearsEncodingOfWrappedResponse(t *testing.T) { e := New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() @@ -1489,7 +1510,7 @@ func TestDefaultHTTPErrorHandler_KeepsEncodingOfWrappedResponse(t *testing.T) { DefaultHTTPErrorHandler(false)(c, ErrNotFound) assert.Equal(t, http.StatusNotFound, rec.Code) - assert.Equal(t, "gzip", rec.Header().Get(HeaderContentEncoding)) + assert.Empty(t, rec.Header().Get(HeaderContentEncoding)) assert.Empty(t, rec.Header().Get(HeaderContentLength)) } diff --git a/middleware/compress.go b/middleware/compress.go index b551b6ce6..28ddbeeeb 100644 --- a/middleware/compress.go +++ b/middleware/compress.go @@ -156,6 +156,11 @@ func (config GzipConfig) ToMiddleware() (echo.MiddlewareFunc, error) { } func (w *gzipResponseWriter) WriteHeader(code int) { + if code >= 100 && code < 200 && code != http.StatusSwitchingProtocols { + // Informational responses precede the final status and are never compressed. + w.ResponseWriter.WriteHeader(code) + return + } if w.passthrough { w.ResponseWriter.WriteHeader(code) return @@ -202,14 +207,7 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) { func (w *gzipResponseWriter) Flush() { if w.passThroughIfEncoded() { - if !w.wroteHeader { - // Commit through echo.Response so the error handler sees the response as written. - w.wroteHeader = true - w.code = http.StatusOK - if r, err := echo.UnwrapResponse(w.ResponseWriter); err == nil && !r.Committed { - r.WriteHeader(http.StatusOK) - } - } + // echo.Response.Flush commits the status if nothing was written yet. _ = http.NewResponseController(w.ResponseWriter).Flush() return } diff --git a/middleware/compress_test.go b/middleware/compress_test.go index 7b5794e31..4914d7186 100644 --- a/middleware/compress_test.go +++ b/middleware/compress_test.go @@ -6,10 +6,13 @@ package middleware import ( "bytes" "compress/gzip" + "context" "fmt" "io" "net/http" "net/http/httptest" + "net/http/httptrace" + "net/textproto" "os" "strconv" "strings" @@ -347,6 +350,41 @@ func TestGzip_PassthroughFlushCommitsResponse(t *testing.T) { assert.Empty(t, rec.Body.String()) } +func TestGzip_ForwardsInformationalStatus(t *testing.T) { + e := echo.New() + e.Use(Gzip()) + e.GET("/", func(c *echo.Context) error { + c.Response().Header().Set("Link", "; rel=preload; as=style") + c.Response().WriteHeader(http.StatusEarlyHints) + return c.String(http.StatusCreated, "ok") + }) + srv := httptest.NewServer(e) + defer srv.Close() + + var informational []int + trace := &httptrace.ClientTrace{ + Got1xxResponse: func(code int, _ textproto.MIMEHeader) error { + informational = append(informational, code) + return nil + }, + } + req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) + res, err := (&http.Transport{DisableCompression: true}).RoundTrip(req) + require.NoError(t, err) + defer res.Body.Close() + + assert.Equal(t, []int{http.StatusEarlyHints}, informational) + assert.Equal(t, http.StatusCreated, res.StatusCode) + reader, err := gzip.NewReader(res.Body) + require.NoError(t, err) + defer reader.Close() + body, err := io.ReadAll(reader) + require.NoError(t, err) + assert.Equal(t, "ok", string(body)) +} + func TestGzip_FlushWithoutWriteProducesValidStream(t *testing.T) { e := echo.New() e.Use(Gzip()) diff --git a/response.go b/response.go index 26697eaa6..13eb93943 100644 --- a/response.go +++ b/response.go @@ -52,7 +52,7 @@ func (r *Response) WriteHeader(code int) { r.logger.Error("echo: response already written to client") return } - if code >= 100 && code < 200 && code != http.StatusSwitchingProtocols { + if isInformationalStatus(code) { // Informational responses precede the final status and do not commit the response. r.ResponseWriter.WriteHeader(code) return @@ -85,6 +85,9 @@ func (r *Response) Write(b []byte) (n int, err error) { // buffered data to the client. // See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) func (r *Response) Flush() { + if !supportsFlush(r.ResponseWriter) { + panic(fmt.Errorf("echo: response writer %T does not support flushing (http.Flusher interface)", r.ResponseWriter)) + } if !r.Committed { // Flushing sends the headers, so commit them the same way Write does. if r.Status == 0 { @@ -144,6 +147,27 @@ func UnwrapResponse(rw http.ResponseWriter) (*Response, error) { } } +// isInformationalStatus reports whether code is a 1xx status that precedes the final one. +// 101 Switching Protocols is final. +func isInformationalStatus(code int) bool { + return code >= 100 && code < 200 && code != http.StatusSwitchingProtocols +} + +// supportsFlush reports whether rw, or a writer it unwraps to, can flush. +// It follows the same lookup as http.ResponseController. +func supportsFlush(rw http.ResponseWriter) bool { + for { + switch t := rw.(type) { + case interface{ FlushError() error }, http.Flusher: + return true + case interface{ Unwrap() http.ResponseWriter }: + rw = t.Unwrap() + default: + return false + } + } +} + // delayedStatusWriter is a wrapper around http.ResponseWriter that delays writing the status code until first Write is called. // This allows (global) error handler to decide correct status code to be sent to the client. type delayedStatusWriter struct { @@ -153,6 +177,10 @@ type delayedStatusWriter struct { } func (w *delayedStatusWriter) WriteHeader(statusCode int) { + if isInformationalStatus(statusCode) { + w.ResponseWriter.WriteHeader(statusCode) + return + } // in case something else writes status code explicitly before us we need mark response committed w.committed = true w.ResponseWriter.WriteHeader(statusCode) @@ -170,6 +198,14 @@ func (w *delayedStatusWriter) Write(data []byte) (int, error) { } func (w *delayedStatusWriter) Flush() { + if !w.committed && supportsFlush(w.ResponseWriter) { + // Flushing sends the headers, so send the delayed status first. + w.committed = true + if w.status == 0 { + w.status = http.StatusOK + } + w.ResponseWriter.WriteHeader(w.status) + } err := http.NewResponseController(w.ResponseWriter).Flush() if err != nil && errors.Is(err, http.ErrNotSupported) { panic(errors.New("response writer flushing is not supported")) @@ -209,6 +245,10 @@ func (w *headResponseWriter) WriteHeader(code int) { if w.wroteStatus { return } + if isInformationalStatus(code) { + w.rw.WriteHeader(code) + return + } w.wroteStatus = true w.status = code if r, err := UnwrapResponse(w.rw); err == nil { diff --git a/response_test.go b/response_test.go index 24fde4000..96c629ec2 100644 --- a/response_test.go +++ b/response_test.go @@ -469,12 +469,15 @@ func TestResponse_WriteHeader_Informational(t *testing.T) { defer srv.Close() var status int + var committedAfter1xx bool e.GET("/", func(c *Context) error { c.Response().Header().Set("Link", "; rel=preload; as=style") c.Response().WriteHeader(http.StatusEarlyHints) r, err := UnwrapResponse(c.Response()) - require.NoError(t, err) - assert.False(t, r.Committed) + if err != nil { + return err + } + committedAfter1xx = r.Committed err = c.String(http.StatusCreated, "ok") status = r.Status return err @@ -496,7 +499,54 @@ func TestResponse_WriteHeader_Informational(t *testing.T) { require.NoError(t, err) assert.Equal(t, []int{http.StatusEarlyHints}, informational) + assert.False(t, committedAfter1xx) assert.Equal(t, http.StatusCreated, res.StatusCode) assert.Equal(t, "ok", string(body)) assert.Equal(t, http.StatusCreated, status) } + +func TestResponse_Flush_PanicsBeforeCommit(t *testing.T) { + e := New() + res := NewResponse(new(testResponseWriter), e.Logger) + beforeCalled := false + res.Before(func() { beforeCalled = true }) + + assert.Panics(t, func() { res.Flush() }) + assert.False(t, res.Committed) + assert.False(t, beforeCalled) +} + +func TestHeadResponseWriter_WriteHeader_Informational(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + res := NewResponse(rec, e.Logger) + w := &headResponseWriter{rw: res} + + w.WriteHeader(http.StatusEarlyHints) + assert.False(t, w.wroteStatus) + assert.False(t, res.Committed) + + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte("ok")) + w.commit() + + assert.Equal(t, http.StatusCreated, res.Status) + assert.Equal(t, "2", rec.Header().Get(HeaderContentLength)) +} + +func TestDelayedStatusWriter_Flush_SendsDelayedStatus(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + res := NewResponse(rec, e.Logger) + w := &delayedStatusWriter{ResponseWriter: res, status: http.StatusCreated} + + w.WriteHeader(http.StatusEarlyHints) + assert.False(t, w.committed) + w.Flush() + _, _ = w.Write([]byte("ok")) + + // httptest.ResponseRecorder keeps the first status it sees, including 1xx, so check Response. + assert.Equal(t, http.StatusCreated, res.Status) + assert.True(t, res.Committed) + assert.True(t, rec.Flushed) +} diff --git a/rfc9457.go b/rfc9457.go index 2719b536e..a4df58a71 100644 --- a/rfc9457.go +++ b/rfc9457.go @@ -118,6 +118,7 @@ func ProblemDetailsHTTPErrorHandler(exposeError bool) HTTPErrorHandler { problem.Title = http.StatusText(problem.Status) } + clearRepresentationHeaders(c.Response().Header()) c.Response().Header().Set(HeaderContentType, MIMEApplicationProblemJSON) var cErr error From d3e09f9291e741faea44511c0950ba740c4bc13c Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Fri, 20 Nov 2026 07:40:14 -0800 Subject: [PATCH 3/4] fix: keep Content-Range on errors and check flush support through wrappers - Restore DefaultHTTPErrorHandler's doc comment, which the helper had displaced. - Keep Content-Range, which a 416 error response carries. - supportsFlush now follows Unwrap to the innermost writer, so a wrapper that defines Flush (such as delayedStatusWriter over Response) no longer commits before a flush that will panic. The check runs only before the first commit. - Close the test transport's idle connections. Co-Authored-By: Claude Opus 5.5 --- echo.go | 18 +++++++++--------- echo_test.go | 3 +-- middleware/compress_test.go | 4 +++- response.go | 27 +++++++++++++++------------ response_test.go | 10 ++++++++++ 5 files changed, 38 insertions(+), 24 deletions(-) diff --git a/echo.go b/echo.go index 762493a3b..658694ff9 100644 --- a/echo.go +++ b/echo.go @@ -452,24 +452,16 @@ func (e *Echo) Router() Router { return e.router } -// DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response -// with status code. `exposeError` parameter decides if returned message will contain also error message or not -// -// Note: DefaultHTTPErrorHandler does not log errors. Use middleware for it if errors need to be logged (separately) -// Note: In case errors happens in middleware call-chain that is returning from handler (which did not return an error). -// When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from -// handler. Then the error that global error handler received will be ignored because we have already "committed" the -// response and status code header has been sent to the client. // clearRepresentationHeaders removes headers that described the response the // handler meant to send, so they are not applied to the error body that replaces it. // A middleware that encodes the error body sets its own Content-Encoding. +// Content-Range is kept because a 416 error response carries it. func clearRepresentationHeaders(h http.Header) { for _, name := range []string{ HeaderContentEncoding, HeaderContentLength, HeaderContentType, HeaderContentDisposition, - "Content-Range", "ETag", HeaderLastModified, } { @@ -477,6 +469,14 @@ func clearRepresentationHeaders(h http.Header) { } } +// DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response +// with status code. `exposeError` parameter decides if returned message will contain also error message or not +// +// Note: DefaultHTTPErrorHandler does not log errors. Use middleware for it if errors need to be logged (separately) +// Note: In case errors happens in middleware call-chain that is returning from handler (which did not return an error). +// When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from +// handler. Then the error that global error handler received will be ignored because we have already "committed" the +// response and status code header has been sent to the client. func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler { return func(c *Context, err error) { if r, _ := UnwrapResponse(c.response); r != nil && r.Committed { diff --git a/echo_test.go b/echo_test.go index c52a34a7c..05f1da8b2 100644 --- a/echo_test.go +++ b/echo_test.go @@ -1470,7 +1470,6 @@ func TestHTTPErrorHandlers_ClearRepresentationHeaders(t *testing.T) { h.Set(HeaderContentLength, "5000") h.Set(HeaderContentType, "text/csv") h.Set(HeaderContentDisposition, `attachment; filename="report.csv"`) - h.Set("Content-Range", "bytes 0-99/5000") h.Set("ETag", `"v1"`) h.Set(HeaderLastModified, "Wed, 21 Oct 2015 07:28:00 GMT") h.Set("X-Request-Id", "keep") @@ -1481,7 +1480,7 @@ func TestHTTPErrorHandlers_ClearRepresentationHeaders(t *testing.T) { e.ServeHTTP(rec, req) assert.Equal(t, http.StatusNotFound, rec.Code) - for _, name := range []string{HeaderContentEncoding, HeaderContentLength, HeaderContentDisposition, "Content-Range", "ETag", HeaderLastModified} { + for _, name := range []string{HeaderContentEncoding, HeaderContentLength, HeaderContentDisposition, "ETag", HeaderLastModified} { assert.Empty(t, rec.Header().Get(name), name) } assert.Equal(t, tt.contentType, rec.Header().Get(HeaderContentType)) diff --git a/middleware/compress_test.go b/middleware/compress_test.go index 4914d7186..96ef66891 100644 --- a/middleware/compress_test.go +++ b/middleware/compress_test.go @@ -371,7 +371,9 @@ func TestGzip_ForwardsInformationalStatus(t *testing.T) { req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, srv.URL, nil) require.NoError(t, err) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) - res, err := (&http.Transport{DisableCompression: true}).RoundTrip(req) + tr := &http.Transport{DisableCompression: true} + defer tr.CloseIdleConnections() + res, err := tr.RoundTrip(req) require.NoError(t, err) defer res.Body.Close() diff --git a/response.go b/response.go index 13eb93943..72226e59a 100644 --- a/response.go +++ b/response.go @@ -85,10 +85,10 @@ func (r *Response) Write(b []byte) (n int, err error) { // buffered data to the client. // See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) func (r *Response) Flush() { - if !supportsFlush(r.ResponseWriter) { - panic(fmt.Errorf("echo: response writer %T does not support flushing (http.Flusher interface)", r.ResponseWriter)) - } if !r.Committed { + if !supportsFlush(r.ResponseWriter) { + panic(fmt.Errorf("echo: response writer %T does not support flushing (http.Flusher interface)", r.ResponseWriter)) + } // Flushing sends the headers, so commit them the same way Write does. if r.Status == 0 { r.Status = http.StatusOK @@ -153,18 +153,21 @@ func isInformationalStatus(code int) bool { return code >= 100 && code < 200 && code != http.StatusSwitchingProtocols } -// supportsFlush reports whether rw, or a writer it unwraps to, can flush. -// It follows the same lookup as http.ResponseController. +// supportsFlush reports whether flushing rw reaches a writer that can flush. +// A wrapper that can unwrap is assumed to delegate flushing, so the check +// continues to the writer it wraps. func supportsFlush(rw http.ResponseWriter) bool { for { - switch t := rw.(type) { - case interface{ FlushError() error }, http.Flusher: - return true - case interface{ Unwrap() http.ResponseWriter }: - rw = t.Unwrap() - default: - return false + u, canUnwrap := rw.(interface{ Unwrap() http.ResponseWriter }) + if !canUnwrap { + switch rw.(type) { + case interface{ FlushError() error }, http.Flusher: + return true + default: + return false + } } + rw = u.Unwrap() } } diff --git a/response_test.go b/response_test.go index 96c629ec2..a89d50c8d 100644 --- a/response_test.go +++ b/response_test.go @@ -550,3 +550,13 @@ func TestDelayedStatusWriter_Flush_SendsDelayedStatus(t *testing.T) { assert.True(t, res.Committed) assert.True(t, rec.Flushed) } + +func TestDelayedStatusWriter_Flush_PanicsBeforeCommit(t *testing.T) { + e := New() + res := NewResponse(new(testResponseWriter), e.Logger) + w := &delayedStatusWriter{ResponseWriter: res, status: http.StatusCreated} + + assert.Panics(t, func() { w.Flush() }) + assert.False(t, w.committed) + assert.False(t, res.Committed) +} From 4639780e1f3f6592d04e2e7cf8f602c9c450b668 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Fri, 20 Nov 2026 07:44:22 -0800 Subject: [PATCH 4/4] fix: narrow error header cleanup and match ResponseController flush lookup - Error handlers now clear only Content-Encoding, Content-Length and Content-Disposition. Content-Type and validators such as ETag can be meant for the error response (a vendor media type, a 304), so they are kept as before. - supportsFlush follows the same lookup as http.ResponseController and only looks through *Response, whose Flush just delegates. A wrapper that flushes itself is no longer rejected because the writer it wraps cannot flush. Co-Authored-By: Claude Opus 5.5 --- echo.go | 22 ++++++++-------------- echo_test.go | 7 ++----- response.go | 26 ++++++++++++++------------ response_test.go | 19 +++++++++++++++++++ 4 files changed, 43 insertions(+), 31 deletions(-) diff --git a/echo.go b/echo.go index 658694ff9..5181ec381 100644 --- a/echo.go +++ b/echo.go @@ -452,21 +452,15 @@ func (e *Echo) Router() Router { return e.router } -// clearRepresentationHeaders removes headers that described the response the -// handler meant to send, so they are not applied to the error body that replaces it. -// A middleware that encodes the error body sets its own Content-Encoding. -// Content-Range is kept because a 416 error response carries it. +// clearRepresentationHeaders removes headers that described the body the handler +// meant to send and are wrong for the error body that replaces it. A middleware +// that encodes the error body sets its own Content-Encoding. Content-Type and +// validators such as ETag are kept because they can be meant for the error +// response, for example a vendor media type or a 304. func clearRepresentationHeaders(h http.Header) { - for _, name := range []string{ - HeaderContentEncoding, - HeaderContentLength, - HeaderContentType, - HeaderContentDisposition, - "ETag", - HeaderLastModified, - } { - h.Del(name) - } + h.Del(HeaderContentEncoding) + h.Del(HeaderContentLength) + h.Del(HeaderContentDisposition) } // DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response diff --git a/echo_test.go b/echo_test.go index 05f1da8b2..86c98ba4f 100644 --- a/echo_test.go +++ b/echo_test.go @@ -1468,11 +1468,8 @@ func TestHTTPErrorHandlers_ClearRepresentationHeaders(t *testing.T) { h := c.Response().Header() h.Set(HeaderContentEncoding, "br") h.Set(HeaderContentLength, "5000") - h.Set(HeaderContentType, "text/csv") h.Set(HeaderContentDisposition, `attachment; filename="report.csv"`) h.Set("ETag", `"v1"`) - h.Set(HeaderLastModified, "Wed, 21 Oct 2015 07:28:00 GMT") - h.Set("X-Request-Id", "keep") return ErrNotFound }) req := httptest.NewRequest(http.MethodGet, "/", nil) @@ -1480,11 +1477,11 @@ func TestHTTPErrorHandlers_ClearRepresentationHeaders(t *testing.T) { e.ServeHTTP(rec, req) assert.Equal(t, http.StatusNotFound, rec.Code) - for _, name := range []string{HeaderContentEncoding, HeaderContentLength, HeaderContentDisposition, "ETag", HeaderLastModified} { + for _, name := range []string{HeaderContentEncoding, HeaderContentLength, HeaderContentDisposition} { assert.Empty(t, rec.Header().Get(name), name) } assert.Equal(t, tt.contentType, rec.Header().Get(HeaderContentType)) - assert.Equal(t, "keep", rec.Header().Get("X-Request-Id")) + assert.Equal(t, `"v1"`, rec.Header().Get("ETag")) }) } } diff --git a/response.go b/response.go index 72226e59a..e6adea77c 100644 --- a/response.go +++ b/response.go @@ -153,21 +153,23 @@ func isInformationalStatus(code int) bool { return code >= 100 && code < 200 && code != http.StatusSwitchingProtocols } -// supportsFlush reports whether flushing rw reaches a writer that can flush. -// A wrapper that can unwrap is assumed to delegate flushing, so the check -// continues to the writer it wraps. +// supportsFlush reports whether http.ResponseController can flush rw. It uses +// the same lookup, except that *Response is skipped because its Flush only +// delegates to the writer it wraps. func supportsFlush(rw http.ResponseWriter) bool { for { - u, canUnwrap := rw.(interface{ Unwrap() http.ResponseWriter }) - if !canUnwrap { - switch rw.(type) { - case interface{ FlushError() error }, http.Flusher: - return true - default: - return false - } + if r, ok := rw.(*Response); ok { + rw = r.ResponseWriter + continue + } + switch t := rw.(type) { + case interface{ FlushError() error }, http.Flusher: + return true + case interface{ Unwrap() http.ResponseWriter }: + rw = t.Unwrap() + default: + return false } - rw = u.Unwrap() } } diff --git a/response_test.go b/response_test.go index a89d50c8d..2caac2577 100644 --- a/response_test.go +++ b/response_test.go @@ -560,3 +560,22 @@ func TestDelayedStatusWriter_Flush_PanicsBeforeCommit(t *testing.T) { assert.False(t, w.committed) assert.False(t, res.Committed) } + +type flushingWrapper struct { + http.ResponseWriter + flushed bool +} + +func (w *flushingWrapper) Flush() { w.flushed = true } + +func (w *flushingWrapper) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func TestResponse_Flush_UsesWrapperFlush(t *testing.T) { + e := New() + w := &flushingWrapper{ResponseWriter: new(testResponseWriter)} + res := NewResponse(w, e.Logger) + + assert.NotPanics(t, func() { res.Flush() }) + assert.True(t, w.flushed) + assert.True(t, res.Committed) +}