Skip to content

Commit

Permalink
Merge pull request #22 from bentranter/add-json-indent-method
Browse files Browse the repository at this point in the history
Add JSONIndent method
  • Loading branch information
dinever committed Apr 28, 2016
2 parents b1a9013 + dfb8a41 commit 8c0be55
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
10 changes: 10 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,16 @@ func (ctx *Context) JSON(obj interface{}) {
ctx.Send(json)
}

// JSONIndent Sends a JSON response, indenting the JSON as desired.
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) {
jsonIndented, err := json.MarshalIndent(obj, prefix, indent)
if err != nil {
panic(err)
}
ctx.SetHeader("Content-Type", "application/json")
ctx.Send(jsonIndented)
}

// Send the response immediately. Set `ctx.IsSent` to `true` to make
// sure that the response won't be sent twice.
func (ctx *Context) Send(body interface{}) {
Expand Down
25 changes: 25 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,28 @@ func TestJSON(t *testing.T) {
assertEqual(t, w.HeaderMap.Get("Content-Type"), `application/json`)
}
}

func TestJSONIndent(t *testing.T) {
cases := []struct {
input map[string]interface{}
output string
}{
{
map[string]interface{}{"status": "success", "code": 200},
`{
"code": 200,
"status": "success"
}`,
},
}

for _, c := range cases {
r := makeTestHTTPRequest(nil, "GET", "/")
w := httptest.NewRecorder()
app := New()
ctx := NewContext(r, w, app)
ctx.JSONIndent(c.input, "", " ")
assertEqual(t, w.Body.String(), c.output)
assertEqual(t, w.HeaderMap.Get("Content-Type"), `application/json`)
}
}

0 comments on commit 8c0be55

Please # to comment.