-
Notifications
You must be signed in to change notification settings - Fork 383
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
Showing
2 changed files
with
24 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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, | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
ant0ine
Author
Owner
|
||
) | ||
} | ||
} | ||
|
||
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() { | ||
|
The test does not seem to match the error message: if the charset is empty no error is produced. This should probably be
charset == "" || strings.ToUpper(charset) != "UTF-8"
.