diff --git a/context_test.go b/context_test.go index f6083070..a638d6dd 100644 --- a/context_test.go +++ b/context_test.go @@ -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) { diff --git a/render/json.go b/render/json.go index f28cd1f8..32e6058d 100644 --- a/render/json.go +++ b/render/json.go @@ -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) } diff --git a/render/render.go b/render/render.go index eadc31b8..994fcd7c 100644 --- a/render/render.go +++ b/render/render.go @@ -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 + } +} diff --git a/render/text.go b/render/text.go index 22a8c99a..5a9e280b 100644 --- a/render/text.go +++ b/render/text.go @@ -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 {