Skip to content

Commit d6f4660

Browse files
tmthrgdjprobinson
authored andcommitted
Only flush once startGzip has been called
This fixes #58 and prevents the underlying Flusher from writing the wrong status code or writing headers before Content-Encoding has been set. This is tmthrgd/gziphandler@cb0f3d94c6 with the test case taken from tmthrgd/gziphandler@574da8f22d.
1 parent 6c51bf0 commit d6f4660

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

gzip.go

+8-2
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,16 @@ func (w *GzipResponseWriter) Close() error {
192192
// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter
193193
// an http.Flusher.
194194
func (w *GzipResponseWriter) Flush() {
195-
if w.gw != nil {
196-
w.gw.Flush()
195+
if w.gw == nil {
196+
// Only flush once startGzip has been called.
197+
//
198+
// Flush is thus a no-op until the written body
199+
// exceeds minSize.
200+
return
197201
}
198202

203+
w.gw.Flush()
204+
199205
if fw, ok := w.ResponseWriter.(http.Flusher); ok {
200206
fw.Flush()
201207
}

gzip_test.go

+18
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,24 @@ func TestStatusCodes(t *testing.T) {
306306
}
307307
}
308308

309+
func TestFlushBeforeWrite(t *testing.T) {
310+
b := []byte(testBody)
311+
handler := GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
312+
rw.WriteHeader(http.StatusNotFound)
313+
rw.(http.Flusher).Flush()
314+
rw.Write(b)
315+
}))
316+
r := httptest.NewRequest(http.MethodGet, "/", nil)
317+
r.Header.Set("Accept-Encoding", "gzip")
318+
w := httptest.NewRecorder()
319+
handler.ServeHTTP(w, r)
320+
321+
res := w.Result()
322+
assert.Equal(t, http.StatusNotFound, res.StatusCode)
323+
assert.Equal(t, "gzip", res.Header.Get("Content-Encoding"))
324+
assert.NotEqual(t, b, w.Body.Bytes())
325+
}
326+
309327
func TestIgnoreSubsequentWriteHeader(t *testing.T) {
310328
handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
311329
w.WriteHeader(500)

0 commit comments

Comments
 (0)