diff --git a/header.go b/header.go index a6b09c6..091e6c5 100644 --- a/header.go +++ b/header.go @@ -1051,7 +1051,12 @@ func (h *ResponseHeader) AppendBytes(dst []byte) []byte { dst = appendHeaderLine(dst, strServer, server) dst = appendHeaderLine(dst, strDate, serverDate.Load().([]byte)) - dst = appendHeaderLine(dst, strContentType, h.ContentType()) + // Append Content-Type only for non-zero responses + // or if it is explicitly set. + // See https://github.com/valyala/fasthttp/issues/28 . + if h.ContentLength() != 0 || len(h.contentType) > 0 { + dst = appendHeaderLine(dst, strContentType, h.ContentType()) + } if len(h.contentLengthBytes) > 0 { dst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes) diff --git a/header_regression_test.go b/header_regression_test.go index f3c425f..69a5775 100644 --- a/header_regression_test.go +++ b/header_regression_test.go @@ -3,9 +3,43 @@ package fasthttp import ( "bufio" "bytes" + "fmt" + "strings" "testing" ) +func TestIssue28ResponseWithoutBodyNoContentType(t *testing.T) { + var r Response + + // Empty response without content-type + s := r.String() + if strings.Contains(s, "Content-Type") { + t.Fatalf("unexpected Content-Type found in response header with empty body: %q", s) + } + + // Explicitly set content-type + r.Header.SetContentType("foo/bar") + s = r.String() + if !strings.Contains(s, "Content-Type: foo/bar\r\n") { + t.Fatalf("missing explicitly set content-type for empty response: %q", s) + } + + // Non-empty response. + r.Reset() + r.SetBodyString("foobar") + s = r.String() + if !strings.Contains(s, fmt.Sprintf("Content-Type: %s\r\n", defaultContentType)) { + t.Fatalf("missing default content-type for non-empty response: %q", s) + } + + // Non-empty response with custom content-type. + r.Header.SetContentType("aaa/bbb") + s = r.String() + if !strings.Contains(s, "Content-Type: aaa/bbb\r\n") { + t.Fatalf("missing custom content-type: %q", s) + } +} + func TestIssue6RequestHeaderSetContentType(t *testing.T) { testIssue6RequestHeaderSetContentType(t, "GET") testIssue6RequestHeaderSetContentType(t, "POST")