Issue #28: do not set default Content-Type for empty response

This commit is contained in:
Aliaksandr Valialkin
2016-01-04 14:56:49 +02:00
parent 9b0b87c951
commit 69a05ffcaf
2 changed files with 40 additions and 1 deletions
+6 -1
View File
@@ -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)
+34
View File
@@ -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")