Skip to content

Commit 8e14b1b

Browse files
authored
No content-type on no body response code (#1011)
* No content-type on no body response code
1 parent 13a1ce6 commit 8e14b1b

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

gzhttp/compress.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,20 @@ func (w *GzipResponseWriter) init() {
324324
w.gw = w.gwFactory.New(w.ResponseWriter, w.level)
325325
}
326326

327+
// bodyAllowedForStatus reports whether a given response status code
328+
// permits a body. See RFC 7230, section 3.3.
329+
func bodyAllowedForStatus(status int) bool {
330+
switch {
331+
case status >= 100 && status <= 199:
332+
return false
333+
case status == 204:
334+
return false
335+
case status == 304:
336+
return false
337+
}
338+
return true
339+
}
340+
327341
// Close will close the gzip.Writer and will put it back in the gzipWriterPool.
328342
func (w *GzipResponseWriter) Close() error {
329343
if w.ignore {
@@ -340,7 +354,7 @@ func (w *GzipResponseWriter) Close() error {
340354

341355
// Handles the intended case of setting a nil Content-Type (as for http/server or http/fs)
342356
// Set the header only if the key does not exist
343-
if _, ok := w.Header()[contentType]; w.setContentType && !ok {
357+
if _, ok := w.Header()[contentType]; bodyAllowedForStatus(w.code) && w.setContentType && !ok {
344358
w.Header().Set(contentType, ct)
345359
}
346360
}

gzhttp/compress_test.go

+20-1
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,7 @@ func TestFlushAfterWrite3(t *testing.T) {
662662
}
663663
handler := gz(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
664664
rw.WriteHeader(http.StatusOK)
665-
//rw.Write(nil)
665+
// rw.Write(nil)
666666
rw.(http.Flusher).Flush()
667667
}))
668668
r := httptest.NewRequest(http.MethodGet, "/", nil)
@@ -1598,6 +1598,25 @@ var sniffTests = []struct {
15981598
{"Incorrect RAR v5+", []byte("Rar \x1A\x07\x01\x00"), "application/octet-stream"},
15991599
}
16001600

1601+
func TestNoContentTypeWhenNoContent(t *testing.T) {
1602+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1603+
w.WriteHeader(http.StatusNoContent)
1604+
})
1605+
1606+
wrapper, err := NewWrapper()
1607+
assertNil(t, err)
1608+
1609+
req, _ := http.NewRequest("GET", "/", nil)
1610+
req.Header.Set("Accept-Encoding", "gzip")
1611+
resp := httptest.NewRecorder()
1612+
wrapper(handler).ServeHTTP(resp, req)
1613+
res := resp.Result()
1614+
1615+
assertEqual(t, http.StatusNoContent, res.StatusCode)
1616+
assertEqual(t, "", res.Header.Get("Content-Type"))
1617+
1618+
}
1619+
16011620
func TestContentTypeDetect(t *testing.T) {
16021621
for _, tt := range sniffTests {
16031622
t.Run(tt.desc, func(t *testing.T) {

0 commit comments

Comments
 (0)