Skip to content
This repository has been archived by the owner on Mar 16, 2019. It is now read-only.

Commit

Permalink
Merge branch '1.0.7-development'
Browse files Browse the repository at this point in the history
* 1.0.7-development:
  🐛 Add header as fix for #4, WriteJSONWithStatus
  • Loading branch information
bahlo committed Mar 21, 2016
2 parents 3613b1f + 5f8fd7f commit 4de7245
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
30 changes: 30 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 4de7245

Please sign in to comment.