mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 13:02:14 +08:00
RawJSON added to allow writing JSON from bytes
This commit is contained in:
parent
febfd57e0c
commit
a1329c766d
@ -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{}) {
|
||||
|
@ -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) {
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -13,6 +13,7 @@ type Render interface {
|
||||
var (
|
||||
_ Render = JSON{}
|
||||
_ Render = IndentedJSON{}
|
||||
_ Render = RawJSON{}
|
||||
_ Render = XML{}
|
||||
_ Render = String{}
|
||||
_ Render = Redirect{}
|
||||
|
Loading…
x
Reference in New Issue
Block a user