Adds supports for custom JSON Content-type

This commit is contained in:
Manu Mtz-Almeida 2015-06-13 04:29:10 +02:00
parent 22f118f3b6
commit a7c957af7d
4 changed files with 23 additions and 6 deletions

View File

@ -219,6 +219,18 @@ func TestContextRenderJSON(t *testing.T) {
assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}
// Tests that the response is serialized as JSON
// we change the content-type before
func TestContextRenderAPIJSON(t *testing.T) {
c, w, _ := createTestContext()
c.Header("Content-Type", "application/vnd.api+json")
c.JSON(201, H{"foo": "bar"})
assert.Equal(t, w.Code, 201)
assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
}
// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
func TestContextRenderIndentedJSON(t *testing.T) {

View File

@ -26,7 +26,7 @@ func (r JSON) Render(w http.ResponseWriter) error {
}
func (r IndentedJSON) Render(w http.ResponseWriter) error {
w.Header()["Content-Type"] = jsonContentType
writeContentType(w, jsonContentType)
jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
if err != nil {
return err
@ -36,6 +36,6 @@ func (r IndentedJSON) Render(w http.ResponseWriter) error {
}
func WriteJSON(w http.ResponseWriter, obj interface{}) error {
w.Header()["Content-Type"] = jsonContentType
writeContentType(w, jsonContentType)
return json.NewEncoder(w).Encode(obj)
}

View File

@ -21,3 +21,10 @@ var (
_ HTMLRender = HTMLDebug{}
_ HTMLRender = HTMLProduction{}
)
func writeContentType(w http.ResponseWriter, value []string) {
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = value
}
}

View File

@ -23,10 +23,8 @@ func (r String) Render(w http.ResponseWriter) error {
}
func WriteString(w http.ResponseWriter, format string, data []interface{}) {
header := w.Header()
if _, exist := header["Content-Type"]; !exist {
header["Content-Type"] = plainContentType
}
writeContentType(w, plainContentType)
if len(data) > 0 {
fmt.Fprintf(w, format, data...)
} else {