Skip to content

Commit

Permalink
JSON Pretty Print
Browse files Browse the repository at this point in the history
  • Loading branch information
mtojek committed Nov 1, 2015
1 parent f5bf0eb commit 1bfd776
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
14 changes: 13 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,19 @@ func (c *Context) String(code int, format string, a ...interface{}) (err error)

// JSON sends a JSON response with status code.
func (c *Context) JSON(code int, i interface{}) (err error) {
b, err := json.Marshal(i)
return c.JSONPrettyPrint(code, i, false)
}

// JSON sends a pretty printed JSON response with status code.
func (c *Context) JSONPrettyPrint(code int, i interface{}, prettyPrint bool) (err error) {
var b []byte

if prettyPrint {
b, err = json.MarshalIndent(i, " ", " ")
} else {
b, err = json.Marshal(i)
}

if err != nil {
return err
}
Expand Down
21 changes: 21 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func (t *Template) Render(w io.Writer, name string, data interface{}) error {

func TestContext(t *testing.T) {
userJSON := `{"id":"1","name":"Joe"}`
userJSONPrettyPrint := "{\n \"id\": \"1\",\n \"name\": \"Joe\"\n }"
userXML := `<user><id>1</id><name>Joe</name></user>`

req, _ := http.NewRequest(POST, "/", strings.NewReader(userJSON))
Expand Down Expand Up @@ -97,6 +98,26 @@ func TestContext(t *testing.T) {
assert.Equal(t, userJSON, rec.Body.String())
}

// JSONPrettyPrint (pretty)
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
err = c.JSONPrettyPrint(http.StatusOK, user{"1", "Joe"}, true)
if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, ApplicationJSONCharsetUTF8, rec.Header().Get(ContentType))
assert.Equal(t, userJSONPrettyPrint, rec.Body.String())
}

// JSONPrettyPrint (not pretty)
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
err = c.JSONPrettyPrint(http.StatusOK, user{"1", "Joe"}, false)
if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, ApplicationJSONCharsetUTF8, rec.Header().Get(ContentType))
assert.Equal(t, userJSON, rec.Body.String())
}

// JSONP
rec = httptest.NewRecorder()
c = NewContext(req, NewResponse(rec), New())
Expand Down

0 comments on commit 1bfd776

Please sign in to comment.