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
13 changes: 13 additions & 0 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,17 @@ func (e *Echo) Router() Router {
return e.router
}

// 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) {
h.Del(HeaderContentEncoding)
h.Del(HeaderContentLength)
h.Del(HeaderContentDisposition)
}

// 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
//
Expand Down Expand Up @@ -498,6 +509,8 @@ func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler {
result = msg
}

clearRepresentationHeaders(c.Response().Header())

var cErr error
if c.Request().Method == http.MethodHead { // Issue #608
cErr = c.NoContent(code)
Expand Down
58 changes: 58 additions & 0 deletions echo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1452,6 +1452,64 @@ func TestDefaultHTTPErrorHandler(t *testing.T) {
}
}

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(HeaderContentDisposition, `attachment; filename="report.csv"`)
h.Set("ETag", `"v1"`)
return ErrNotFound
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)

assert.Equal(t, http.StatusNotFound, rec.Code)
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, `"v1"`, rec.Header().Get("ETag"))
})
}
}

type encodingResponseWriter struct {
http.ResponseWriter
}

func (w *encodingResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}

func TestDefaultHTTPErrorHandler_ClearsEncodingOfWrappedResponse(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.Empty(t, 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)
Expand Down
14 changes: 6 additions & 8 deletions middleware/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
40 changes: 40 additions & 0 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -347,6 +350,43 @@ 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", "</style.css>; 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)
tr := &http.Transport{DisableCompression: true}
defer tr.CloseIdleConnections()
res, err := tr.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())
Expand Down
57 changes: 57 additions & 0 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ func (r *Response) WriteHeader(code int) {
r.logger.Error("echo: response already written to client")
return
}
if isInformationalStatus(code) {
// 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()
Expand Down Expand Up @@ -80,6 +85,16 @@ 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 {
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
}
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))
Expand Down Expand Up @@ -132,6 +147,32 @@ 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 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 {
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
}
}
}

// 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 {
Expand All @@ -141,6 +182,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)
Expand All @@ -158,6 +203,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"))
Expand Down Expand Up @@ -197,6 +250,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 {
Expand Down
Loading
Loading