From 1bfd7762ca46e666bcc79a16918d7b05e29df781 Mon Sep 17 00:00:00 2001 From: Marcin Tojek Date: Sun, 1 Nov 2015 19:48:55 +0100 Subject: [PATCH] JSON Pretty Print --- context.go | 14 +++++++++++++- context_test.go | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index c25e6465..23f734c0 100644 --- a/context.go +++ b/context.go @@ -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 } diff --git a/context_test.go b/context_test.go index 9bd881ed..e2cdc738 100644 --- a/context_test.go +++ b/context_test.go @@ -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 := `1Joe` req, _ := http.NewRequest(POST, "/", strings.NewReader(userJSON)) @@ -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())