diff --git a/gzhttp/asserts_test.go b/gzhttp/asserts_test.go index 987b848ea0..5bbfd80227 100644 --- a/gzhttp/asserts_test.go +++ b/gzhttp/asserts_test.go @@ -15,7 +15,7 @@ func assertEqual(t testing.TB, want, got interface{}) { func assertNotEqual(t testing.TB, want, got interface{}) { t.Helper() if reflect.DeepEqual(want, got) { - t.Fatalf("want %#v, got %#v", want, got) + t.Fatalf("did not want %#v, got %#v", want, got) } } diff --git a/gzhttp/gzip.go b/gzhttp/gzip.go index dcca6288c8..759845a9e5 100644 --- a/gzhttp/gzip.go +++ b/gzhttp/gzip.go @@ -97,6 +97,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/gzhttp/gzip_test.go b/gzhttp/gzip_test.go index ca5ab9f909..e33e8fa887 100644 --- a/gzhttp/gzip_test.go +++ b/gzhttp/gzip_test.go @@ -649,3 +649,18 @@ func newTestHandler(body string) http.Handler { } })) } + +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) + + assertEqual(t, "", res.Header().Get("Content-Type")) +}