Skip to content

Commit

Permalink
Only flush once startGzip has been called
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
tmthrgd authored and jprobinson committed Nov 20, 2017
1 parent 6c51bf0 commit d6f4660
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
10 changes: 8 additions & 2 deletions gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,16 @@ func (w *GzipResponseWriter) Close() error {
// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter
// an http.Flusher.
func (w *GzipResponseWriter) Flush() {
if w.gw != nil {
w.gw.Flush()
if w.gw == nil {
// Only flush once startGzip has been called.
//
// Flush is thus a no-op until the written body
// exceeds minSize.
return
}

w.gw.Flush()

if fw, ok := w.ResponseWriter.(http.Flusher); ok {
fw.Flush()
}
Expand Down
18 changes: 18 additions & 0 deletions gzip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,24 @@ func TestStatusCodes(t *testing.T) {
}
}

func TestFlushBeforeWrite(t *testing.T) {
b := []byte(testBody)
handler := GzipHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusNotFound)
rw.(http.Flusher).Flush()
rw.Write(b)
}))
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Header.Set("Accept-Encoding", "gzip")
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)

res := w.Result()
assert.Equal(t, http.StatusNotFound, res.StatusCode)
assert.Equal(t, "gzip", res.Header.Get("Content-Encoding"))
assert.NotEqual(t, b, w.Body.Bytes())
}

func TestIgnoreSubsequentWriteHeader(t *testing.T) {
handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
Expand Down

0 comments on commit d6f4660

Please sign in to comment.