Skip to content

Commit

Permalink
No content-type on no body response code
Browse files Browse the repository at this point in the history
  • Loading branch information
juliens committed Sep 27, 2024
1 parent 13a1ce6 commit 6d73e43
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
16 changes: 15 additions & 1 deletion gzhttp/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,20 @@ func (w *GzipResponseWriter) init() {
w.gw = w.gwFactory.New(w.ResponseWriter, w.level)
}

// bodyAllowedForStatus reports whether a given response status code
// permits a body. See RFC 7230, section 3.3.
func bodyAllowedForStatus(status int) bool {
switch {
case status >= 100 && status <= 199:
return false
case status == 204:
return false
case status == 304:
return false
}
return true
}

// Close will close the gzip.Writer and will put it back in the gzipWriterPool.
func (w *GzipResponseWriter) Close() error {
if w.ignore {
Expand All @@ -335,7 +349,7 @@ func (w *GzipResponseWriter) Close() error {
ce = w.Header().Get(contentEncoding)
cr = w.Header().Get(contentRange)
)
if ct == "" {
if ct == "" && bodyAllowedForStatus(w.code) {
ct = http.DetectContentType(w.buf)

// Handles the intended case of setting a nil Content-Type (as for http/server or http/fs)
Expand Down
21 changes: 20 additions & 1 deletion gzhttp/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,7 @@ func TestFlushAfterWrite3(t *testing.T) {
}
handler := gz(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
//rw.Write(nil)
// rw.Write(nil)
rw.(http.Flusher).Flush()
}))
r := httptest.NewRequest(http.MethodGet, "/", nil)
Expand Down Expand Up @@ -1598,6 +1598,25 @@ var sniffTests = []struct {
{"Incorrect RAR v5+", []byte("Rar \x1A\x07\x01\x00"), "application/octet-stream"},
}

func TestNoContentTypeWhenNoContent(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})

wrapper, err := NewWrapper()
assertNil(t, err)

req, _ := http.NewRequest("GET", "/", nil)
req.Header.Set("Accept-Encoding", "gzip")
resp := httptest.NewRecorder()
wrapper(handler).ServeHTTP(resp, req)
res := resp.Result()

assertEqual(t, http.StatusNoContent, res.StatusCode)
assertEqual(t, "", res.Header.Get("Content-Type"))

}

func TestContentTypeDetect(t *testing.T) {
for _, tt := range sniffTests {
t.Run(tt.desc, func(t *testing.T) {
Expand Down

0 comments on commit 6d73e43

Please sign in to comment.