Skip to content

Commit

Permalink
Fixed a problem that returned wrong content-encoding when the gzip co…
Browse files Browse the repository at this point in the history
…mpressed content was empty (#1921)

Fixed a problem that returned wrong content-encoding when the gzip compressed content was empty
  • Loading branch information
orisano authored Dec 15, 2021
1 parent c32fafa commit 7bde9ae
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
9 changes: 4 additions & 5 deletions middleware/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type (
gzipResponseWriter struct {
io.Writer
http.ResponseWriter
wroteBody bool
}
)

Expand Down Expand Up @@ -78,8 +79,9 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
}
rw := res.Writer
w.Reset(rw)
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw}
defer func() {
if res.Size == 0 {
if !grw.wroteBody {
if res.Header().Get(echo.HeaderContentEncoding) == gzipScheme {
res.Header().Del(echo.HeaderContentEncoding)
}
Expand All @@ -92,7 +94,6 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
w.Close()
pool.Put(w)
}()
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw}
res.Writer = grw
}
return next(c)
Expand All @@ -101,9 +102,6 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
}

func (w *gzipResponseWriter) WriteHeader(code int) {
if code == http.StatusNoContent { // Issue #489
w.ResponseWriter.Header().Del(echo.HeaderContentEncoding)
}
w.Header().Del(echo.HeaderContentLength) // Issue #444
w.ResponseWriter.WriteHeader(code)
}
Expand All @@ -112,6 +110,7 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if w.Header().Get(echo.HeaderContentType) == "" {
w.Header().Set(echo.HeaderContentType, http.DetectContentType(b))
}
w.wroteBody = true
return w.Writer.Write(b)
}

Expand Down
21 changes: 21 additions & 0 deletions middleware/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,27 @@ func TestGzipNoContent(t *testing.T) {
}
}

func TestGzipEmpty(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := Gzip()(func(c echo.Context) error {
return c.String(http.StatusOK, "")
})
if assert.NoError(t, h(c)) {
assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding))
assert.Equal(t, "text/plain; charset=UTF-8", rec.Header().Get(echo.HeaderContentType))
r, err := gzip.NewReader(rec.Body)
if assert.NoError(t, err) {
var buf bytes.Buffer
buf.ReadFrom(r)
assert.Equal(t, "", buf.String())
}
}
}

func TestGzipErrorReturned(t *testing.T) {
e := echo.New()
e.Use(Gzip())
Expand Down

0 comments on commit 7bde9ae

Please sign in to comment.