From 5f8fd7fb8a9e66e240245a849afc1d1245ec3959 Mon Sep 17 00:00:00 2001 From: Robin Temme Date: Sat, 14 Mar 2015 15:37:13 +0100 Subject: [PATCH] :bug: Add header as fix for #4, WriteJSONWithStatus --- json.go | 8 ++++++++ json_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/json.go b/json.go index 8730949..548f491 100644 --- a/json.go +++ b/json.go @@ -25,3 +25,11 @@ func WriteJSON(w http.ResponseWriter, v interface{}) error { w.Write(b) return nil } + +// WriteJSONWithStatus writes the given statuscode into the header and the +// given interface as JSON or returns an error +func WriteJSONWithStatus(w http.ResponseWriter, code int, v interface{}) error { + w.WriteHeader(code) + + return WriteJSON(w, v) +} diff --git a/json_test.go b/json_test.go index 77d8009..cca60c8 100644 --- a/json_test.go +++ b/json_test.go @@ -61,3 +61,33 @@ func TestWriteJSON(t *testing.T) { t.Errorf("WriteJSON should return an error, but didn't") } } + +func TestWriteJSONWithStatus(t *testing.T) { + // in + code := 201 + in := map[string]interface{}{ + "foo": "bar", + "bar": "foo", + } + json := `{ + "foo": "bar", + "bar": "foo" +} +` + buf := bytes.NewBufferString(json) + + w := httptest.NewRecorder() + WriteJSONWithStatus(w, code, in) + + // test code + if w.Code != code { + t.Errorf("WriteJSONWithStatus should set Code to %i, but did set it to %i", code, w.Code) + } + + // test body + if w.Body == nil { + t.Errorf("WriteJSONWithStatus should set the Body to %s, but didn't", json) + } else if string(w.Body.Bytes()) == string(buf.Bytes()) { + t.Errorf("WriteJSONWithStatus set the Body to %v, but should set it to %v", buf, w.Body) + } +}