From 3152f30bb246f193be132e9d14e6e4ad174eed50 Mon Sep 17 00:00:00 2001 From: antoine Date: Sat, 28 Nov 2015 00:35:09 +0000 Subject: [PATCH] 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. --- rest/response.go | 6 +++++- rest/test/util.go | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/rest/response.go b/rest/response.go index 8baeae6..52529f1 100644 --- a/rest/response.go +++ b/rest/response.go @@ -66,7 +66,11 @@ type responseWriter struct { func (w *responseWriter) WriteHeader(code int) { if w.Header().Get("Content-Type") == "" { - w.Header().Set("Content-Type", "application/json") + // 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. + w.Header().Set("Content-Type", "application/json; charset=utf-8") } w.ResponseWriter.WriteHeader(code) w.wroteHeader = true diff --git a/rest/test/util.go b/rest/test/util.go index 54fdda4..3b59ba3 100644 --- a/rest/test/util.go +++ b/rest/test/util.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "io/ioutil" + "mime" "net/http" "net/http/httptest" "strings" @@ -56,7 +57,23 @@ func HeaderIs(t *testing.T, r *httptest.ResponseRecorder, headerKey, expectedVal } func ContentTypeIsJson(t *testing.T, r *httptest.ResponseRecorder) { - HeaderIs(t, r, "Content-Type", "application/json") + + mediaType, params, _ := mime.ParseMediaType(r.HeaderMap.Get("Content-Type")) + charset := params["charset"] + + if mediaType != "application/json" { + t.Errorf( + "Content-Type media type: application/json expected, got: %s", + mediaType, + ) + } + + if charset != "" && strings.ToUpper(charset) != "UTF-8" { + t.Errorf( + "Content-Type charset: utf-8 or no charset expected, got: %s", + charset, + ) + } } func ContentEncodingIsGzip(t *testing.T, r *httptest.ResponseRecorder) { @@ -103,7 +120,7 @@ func (rd *Recorded) HeaderIs(headerKey, expectedValue string) { } func (rd *Recorded) ContentTypeIsJson() { - rd.HeaderIs("Content-Type", "application/json") + ContentTypeIsJson(rd.T, rd.Recorder) } func (rd *Recorded) ContentEncodingIsGzip() {