diff --git a/gzip.go b/gzip.go index 957fc92..29b8134 100644 --- a/gzip.go +++ b/gzip.go @@ -128,6 +128,12 @@ func (w *GzipResponseWriter) Write(b []byte) (int, error) { // If a Content-Type wasn't specified, infer it from the current buffer. if ct == "" { ct = http.DetectContentType(w.buf) + } + + // Handles the intended case of setting a nil Content-Type (as for http/server or http/fs) + // Set the header only if the key does not exist + _, haveType := w.Header()["Content-Type"] + if !haveType { w.Header().Set(contentType, ct) } // If the Content-Type is acceptable to GZIP, initialize the GZIP writer. diff --git a/gzip_test.go b/gzip_test.go index bed7f52..07de5f8 100644 --- a/gzip_test.go +++ b/gzip_test.go @@ -81,6 +81,21 @@ func TestGzipHandler(t *testing.T) { assert.Equal(t, http.DetectContentType([]byte(testBody)), res3.Header().Get("Content-Type")) } +func TestGzipHandlerNilContentType(t *testing.T) { + // This just exists to provide something for GzipHandler to wrap. + handler := newTestHandler(testBody) + + // content-type header not set when provided nil + + req, _ := http.NewRequest("GET", "/whatever", nil) + req.Header.Set("Accept-Encoding", "gzip") + res := httptest.NewRecorder() + res.Header()["Content-Type"] = nil + handler.ServeHTTP(res, req) + + assert.Empty(t, res.Header().Get("Content-Type")) +} + func TestGzipHandlerSmallBodyNoCompression(t *testing.T) { handler := newTestHandler(smallTestBody)