Allow user to explicitly set a Content-Type header on ghttp JSON handlers
diff --git a/ghttp/handlers.go b/ghttp/handlers.go index 52fcd43..c3b56a4 100644 --- a/ghttp/handlers.go +++ b/ghttp/handlers.go
@@ -190,7 +190,9 @@ } else { headers = make(http.Header) } - headers["Content-Type"] = []string{"application/json"} + if _, found := headers["Content-Type"]; !found { + headers["Content-Type"] = []string{"application/json"} + } return RespondWith(statusCode, string(data), headers) } @@ -214,7 +216,9 @@ } else { headers = make(http.Header) } - headers["Content-Type"] = []string{"application/json"} + if _, found := headers["Content-Type"]; !found { + headers["Content-Type"] = []string{"application/json"} + } copyHeader(headers, w.Header()) w.WriteHeader(*statusCode) w.Write(data)
diff --git a/ghttp/test_server_test.go b/ghttp/test_server_test.go index 40836a1..82aa3aa 100644 --- a/ghttp/test_server_test.go +++ b/ghttp/test_server_test.go
@@ -583,10 +583,15 @@ }) Context("when optional headers are set", func() { + var headers http.Header BeforeEach(func() { + headers = http.Header{"Stuff": []string{"things"}} + }) + + JustBeforeEach(func() { s.AppendHandlers(CombineHandlers( VerifyRequest("POST", "/foo"), - RespondWithJSONEncoded(http.StatusCreated, []int{1, 2, 3}, http.Header{"Stuff": []string{"things"}}), + RespondWithJSONEncoded(http.StatusCreated, []int{1, 2, 3}, headers), )) }) @@ -603,6 +608,19 @@ Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"})) }) + + Context("when setting the Content-Type explicitly", func() { + BeforeEach(func() { + headers["Content-Type"] = []string{"not-json"} + }) + + It("should use the Content-Type header that was explicitly set", func() { + resp, err = http.Post(s.URL()+"/foo", "application/json", nil) + Ω(err).ShouldNot(HaveOccurred()) + + Ω(resp.Header["Content-Type"]).Should(Equal([]string{"not-json"})) + }) + }) }) }) @@ -650,12 +668,17 @@ }) Context("when optional headers are set", func() { + var headers http.Header BeforeEach(func() { + headers = http.Header{"Stuff": []string{"things"}} + }) + + JustBeforeEach(func() { code = http.StatusOK object = testObject{} s.AppendHandlers(CombineHandlers( VerifyRequest("POST", "/foo"), - RespondWithJSONEncodedPtr(&code, &object, http.Header{"Stuff": []string{"things"}}), + RespondWithJSONEncodedPtr(&code, &object, headers), )) }) @@ -672,6 +695,19 @@ Ω(resp.Header["Content-Type"]).Should(Equal([]string{"application/json"})) }) + + Context("when setting the Content-Type explicitly", func() { + BeforeEach(func() { + headers["Content-Type"] = []string{"not-json"} + }) + + It("should use the Content-Type header that was explicitly set", func() { + resp, err = http.Post(s.URL()+"/foo", "application/json", nil) + Ω(err).ShouldNot(HaveOccurred()) + + Ω(resp.Header["Content-Type"]).Should(Equal([]string{"not-json"})) + }) + }) }) }) })