Skip to content

Commit 3152f30

Browse files
committed
Include charset=utf-8 in the JSON response.
Per spec, UTF-8 is the default, and the charset parameter should not be necessary. But some clients (eg: Chrome) think otherwise. Since json.Marshal produces UTF-8, setting the charset parameter is a safe option. This changeset also includes a better ContentTypeIsJson test method. It expects the charset to be utf-8 or not set.
1 parent 1eb58eb commit 3152f30

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

rest/response.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,11 @@ type responseWriter struct {
6666

6767
func (w *responseWriter) WriteHeader(code int) {
6868
if w.Header().Get("Content-Type") == "" {
69-
w.Header().Set("Content-Type", "application/json")
69+
// Per spec, UTF-8 is the default, and the charset parameter should not
70+
// be necessary. But some clients (eg: Chrome) think otherwise.
71+
// Since json.Marshal produces UTF-8, setting the charset parameter is a
72+
// safe option.
73+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
7074
}
7175
w.ResponseWriter.WriteHeader(code)
7276
w.wroteHeader = true

rest/test/util.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/json"
55
"fmt"
66
"io/ioutil"
7+
"mime"
78
"net/http"
89
"net/http/httptest"
910
"strings"
@@ -56,7 +57,23 @@ func HeaderIs(t *testing.T, r *httptest.ResponseRecorder, headerKey, expectedVal
5657
}
5758

5859
func ContentTypeIsJson(t *testing.T, r *httptest.ResponseRecorder) {
59-
HeaderIs(t, r, "Content-Type", "application/json")
60+
61+
mediaType, params, _ := mime.ParseMediaType(r.HeaderMap.Get("Content-Type"))
62+
charset := params["charset"]
63+
64+
if mediaType != "application/json" {
65+
t.Errorf(
66+
"Content-Type media type: application/json expected, got: %s",
67+
mediaType,
68+
)
69+
}
70+
71+
if charset != "" && strings.ToUpper(charset) != "UTF-8" {
72+
t.Errorf(
73+
"Content-Type charset: utf-8 or no charset expected, got: %s",
74+
charset,
75+
)
76+
}
6077
}
6178

6279
func ContentEncodingIsGzip(t *testing.T, r *httptest.ResponseRecorder) {
@@ -103,7 +120,7 @@ func (rd *Recorded) HeaderIs(headerKey, expectedValue string) {
103120
}
104121

105122
func (rd *Recorded) ContentTypeIsJson() {
106-
rd.HeaderIs("Content-Type", "application/json")
123+
ContentTypeIsJson(rd.T, rd.Recorder)
107124
}
108125

109126
func (rd *Recorded) ContentEncodingIsGzip() {

0 commit comments

Comments
 (0)