@@ -131,15 +131,15 @@ func (w *GzipResponseWriter) Write(b []byte) (int, error) {
131131
132132 // If the Content-Length is larger than minSize or the current buffer is larger than minSize, then continue.
133133 if cl >= w .minSize || len (w .buf ) >= w .minSize {
134- // If a Content-Type wasn't specified, infer it from the current buffer.
135- if ct == "" {
134+ // If a Content-Type wasn't specified, infer it from the current buffer when the response has a body .
135+ if ct == "" && bodyAllowedForStatus ( w . code ) && len ( w . buf ) > 0 {
136136 ct = http .DetectContentType (w .buf )
137- }
138137
139- // Handles the intended case of setting a nil Content-Type (as for http/server or http/fs)
140- // Set the header only if the key does not exist
141- if _ , ok := hdr [contentType ]; w .setContentType && ! ok {
142- hdr .Set (contentType , ct )
138+ // Handles the intended case of setting a nil Content-Type (as for http/server or http/fs)
139+ // Set the header only if the key does not exist
140+ if _ , ok := hdr [contentType ]; w .setContentType && ! ok {
141+ hdr .Set (contentType , ct )
142+ }
143143 }
144144
145145 // If the Content-Type is acceptable to GZIP, initialize the GZIP writer.
@@ -349,12 +349,14 @@ func (w *GzipResponseWriter) Close() error {
349349 ce = w .Header ().Get (contentEncoding )
350350 cr = w .Header ().Get (contentRange )
351351 )
352- if ct == "" {
352+
353+ // Detects the response content-type when it does not exist and the response has a body.
354+ if ct == "" && bodyAllowedForStatus (w .code ) && len (w .buf ) > 0 {
353355 ct = http .DetectContentType (w .buf )
354356
355357 // Handles the intended case of setting a nil Content-Type (as for http/server or http/fs)
356358 // Set the header only if the key does not exist
357- if _ , ok := w .Header ()[contentType ]; bodyAllowedForStatus ( w . code ) && w .setContentType && ! ok {
359+ if _ , ok := w .Header ()[contentType ]; w .setContentType && ! ok {
358360 w .Header ().Set (contentType , ct )
359361 }
360362 }
@@ -393,7 +395,8 @@ func (w *GzipResponseWriter) Flush() {
393395 cr = w .Header ().Get (contentRange )
394396 )
395397
396- if ct == "" {
398+ // Detects the response content-type when it does not exist and the response has a body.
399+ if ct == "" && bodyAllowedForStatus (w .code ) && len (w .buf ) > 0 {
397400 ct = http .DetectContentType (w .buf )
398401
399402 // Handles the intended case of setting a nil Content-Type (as for http/server or http/fs)
0 commit comments