Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set detected Content-Type only when not already set #96

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions gzip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down