Skip to content

Commit 7bde9ae

Browse files
authored
Fixed a problem that returned wrong content-encoding when the gzip compressed content was empty (#1921)
Fixed a problem that returned wrong content-encoding when the gzip compressed content was empty
1 parent c32fafa commit 7bde9ae

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

middleware/compress.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ type (
2727
gzipResponseWriter struct {
2828
io.Writer
2929
http.ResponseWriter
30+
wroteBody bool
3031
}
3132
)
3233

@@ -78,8 +79,9 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
7879
}
7980
rw := res.Writer
8081
w.Reset(rw)
82+
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw}
8183
defer func() {
82-
if res.Size == 0 {
84+
if !grw.wroteBody {
8385
if res.Header().Get(echo.HeaderContentEncoding) == gzipScheme {
8486
res.Header().Del(echo.HeaderContentEncoding)
8587
}
@@ -92,7 +94,6 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
9294
w.Close()
9395
pool.Put(w)
9496
}()
95-
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw}
9697
res.Writer = grw
9798
}
9899
return next(c)
@@ -101,9 +102,6 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc {
101102
}
102103

103104
func (w *gzipResponseWriter) WriteHeader(code int) {
104-
if code == http.StatusNoContent { // Issue #489
105-
w.ResponseWriter.Header().Del(echo.HeaderContentEncoding)
106-
}
107105
w.Header().Del(echo.HeaderContentLength) // Issue #444
108106
w.ResponseWriter.WriteHeader(code)
109107
}
@@ -112,6 +110,7 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
112110
if w.Header().Get(echo.HeaderContentType) == "" {
113111
w.Header().Set(echo.HeaderContentType, http.DetectContentType(b))
114112
}
113+
w.wroteBody = true
115114
return w.Writer.Write(b)
116115
}
117116

middleware/compress_test.go

+21
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,27 @@ func TestGzipNoContent(t *testing.T) {
106106
}
107107
}
108108

109+
func TestGzipEmpty(t *testing.T) {
110+
e := echo.New()
111+
req := httptest.NewRequest(http.MethodGet, "/", nil)
112+
req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme)
113+
rec := httptest.NewRecorder()
114+
c := e.NewContext(req, rec)
115+
h := Gzip()(func(c echo.Context) error {
116+
return c.String(http.StatusOK, "")
117+
})
118+
if assert.NoError(t, h(c)) {
119+
assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding))
120+
assert.Equal(t, "text/plain; charset=UTF-8", rec.Header().Get(echo.HeaderContentType))
121+
r, err := gzip.NewReader(rec.Body)
122+
if assert.NoError(t, err) {
123+
var buf bytes.Buffer
124+
buf.ReadFrom(r)
125+
assert.Equal(t, "", buf.String())
126+
}
127+
}
128+
}
129+
109130
func TestGzipErrorReturned(t *testing.T) {
110131
e := echo.New()
111132
e.Use(Gzip())

0 commit comments

Comments
 (0)