Skip to content

Commit

Permalink
Faster IndentedJSON + unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat committed May 10, 2015
1 parent a9dad53 commit 3df5dfd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 3 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,9 @@ func (c *Context) HTML(code int, name string, obj interface{}) {
}

func (c *Context) IndentedJSON(code int, obj interface{}) {
c.Render(code, render.IndentedJSON, obj)
if err := render.WriteIndentedJSON(c.Writer, code, obj); err != nil {
c.renderingError(err, obj)
}
}

// Serializes the given struct as JSON into the response body in a fast and efficient way.
Expand Down
15 changes: 15 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,17 @@ func TestContextSetGetValues(t *testing.T) {
c.Set("uint64", uint64(42))
c.Set("float32", float32(4.2))
c.Set("float64", 4.2)
var a interface{} = 1
c.Set("intInterface", a)

assert.Exactly(t, c.MustGet("string").(string), "this is a string")
assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
assert.Exactly(t, c.MustGet("intInterface").(int), 1)

}

func TestContextCopy(t *testing.T) {
Expand Down Expand Up @@ -160,6 +164,17 @@ func TestContextRenderJSON(t *testing.T) {
assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}

// Tests that the response is serialized as JSON
// and Content-Type is set to application/json
func TestContextRenderIndentedJSON(t *testing.T) {
c, w, _ := createTestContext()
c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})

assert.Equal(t, w.Code, 201)
assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
}

// Tests that the response executes the templates
// and responds with Content-Type set to text/html
func TestContextRenderHTML(t *testing.T) {
Expand Down

0 comments on commit 3df5dfd

Please sign in to comment.