From a1329c766df82793ebfc5b4878ceb37618355ae5 Mon Sep 17 00:00:00 2001 From: Tyson Maly Date: Mon, 21 Sep 2015 08:10:01 -0400 Subject: [PATCH] RawJSON added to allow writing JSON from bytes --- context.go | 9 +++++++++ context_test.go | 15 +++++++++++++++ render/json.go | 10 ++++++++++ render/render.go | 1 + 4 files changed, 35 insertions(+) diff --git a/context.go b/context.go index b784c14b..56b2bace 100644 --- a/context.go +++ b/context.go @@ -5,6 +5,7 @@ package gin import ( + "bytes" "errors" "io" "math" @@ -358,6 +359,14 @@ func (c *Context) JSON(code int, obj interface{}) { } } +// RawJSON give a buffer of bytes representing JSON just write it out +// this habdles cases where you get back JSON as bytes from redis or ffjson +// and you do not want the extra marshall/demarshal overhead +// It also sets the Content-Type as "application/json". +func (c *Context) RawJSON(code int, obj interface{}) { + c.Render(code, render.RawJSON{Data: obj.(*bytes.Buffer)}) +} + // XML serializes the given struct as XML into the response body. // It also sets the Content-Type as "application/xml". func (c *Context) XML(code int, obj interface{}) { diff --git a/context_test.go b/context_test.go index 14b93208..9c2e8e62 100644 --- a/context_test.go +++ b/context_test.go @@ -257,6 +257,21 @@ func TestContextRenderJSON(t *testing.T) { assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8") } +// Tests that the response is JSON writen out from bytes +// and Content-Type is set to application/json +func TestContextRenderRawJSON(t *testing.T) { + c, w, _ := createTestContext() + + var buffer bytes.Buffer + buffer.WriteString("{\"foo\": \"bar\"}") + + c.RawJSON(201, &buffer) + + assert.Equal(t, w.Code, 201) + assert.Equal(t, w.Body.String(), "{\"foo\": \"bar\"}") + assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8") +} + // Tests that the response is serialized as JSON // we change the content-type before func TestContextRenderAPIJSON(t *testing.T) { diff --git a/render/json.go b/render/json.go index 32e6058d..3e82292a 100644 --- a/render/json.go +++ b/render/json.go @@ -5,6 +5,7 @@ package render import ( + "bytes" "encoding/json" "net/http" ) @@ -17,6 +18,9 @@ type ( IndentedJSON struct { Data interface{} } + RawJSON struct { + Data *bytes.Buffer + } ) var jsonContentType = []string{"application/json; charset=utf-8"} @@ -39,3 +43,9 @@ func WriteJSON(w http.ResponseWriter, obj interface{}) error { writeContentType(w, jsonContentType) return json.NewEncoder(w).Encode(obj) } + +func (r RawJSON) Render(w http.ResponseWriter) error { + writeContentType(w, jsonContentType) + w.Write(r.Data.Bytes()) + return nil +} diff --git a/render/render.go b/render/render.go index 994fcd7c..af85130c 100644 --- a/render/render.go +++ b/render/render.go @@ -13,6 +13,7 @@ type Render interface { var ( _ Render = JSON{} _ Render = IndentedJSON{} + _ Render = RawJSON{} _ Render = XML{} _ Render = String{} _ Render = Redirect{}