add render for ascii

This commit is contained in:
Rex Lee(李俊) 2018-05-16 15:57:44 +08:00
parent bf7803815b
commit f71e5432df
2 changed files with 38 additions and 0 deletions

View File

@ -708,6 +708,12 @@ func (c *Context) JSON(code int, obj interface{}) {
c.Render(code, render.JSON{Data: obj}) c.Render(code, render.JSON{Data: obj})
} }
// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
// It also sets the Content-Type as "application/json".
func (c *Context) AsciiJSON(code int, obj interface{}) {
c.Render(code, render.AsciiJSON{Data: obj})
}
// XML serializes the given struct as XML into the response body. // XML serializes the given struct as XML into the response body.
// It also sets the Content-Type as "application/xml". // It also sets the Content-Type as "application/xml".
func (c *Context) XML(code int, obj interface{}) { func (c *Context) XML(code int, obj interface{}) {

View File

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"html/template" "html/template"
"net/http" "net/http"
"strconv"
"github.com/gin-gonic/gin/json" "github.com/gin-gonic/gin/json"
) )
@ -30,10 +31,15 @@ type JsonpJSON struct {
Data interface{} Data interface{}
} }
type AsciiJSON struct {
Data interface{}
}
type SecureJSONPrefix string type SecureJSONPrefix string
var jsonContentType = []string{"application/json; charset=utf-8"} var jsonContentType = []string{"application/json; charset=utf-8"}
var jsonpContentType = []string{"application/javascript; charset=utf-8"} var jsonpContentType = []string{"application/javascript; charset=utf-8"}
var jsonAsciiContentType = []string{"application/json"}
func (r JSON) Render(w http.ResponseWriter) (err error) { func (r JSON) Render(w http.ResponseWriter) (err error) {
if err = WriteJSON(w, r.Data); err != nil { if err = WriteJSON(w, r.Data); err != nil {
@ -112,3 +118,29 @@ func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {
func (r JsonpJSON) WriteContentType(w http.ResponseWriter) { func (r JsonpJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonpContentType) writeContentType(w, jsonpContentType)
} }
func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {
r.WriteContentType(w)
ret, err := json.Marshal(r.Data)
if err != nil {
return err
}
result := ""
for _, r := range ret {
cvt := ""
if r < 128 {
cvt = string(r)
} else {
cvt = `\u` + strconv.FormatInt(int64(r), 16)
}
result = result + cvt
}
w.Write([]byte(result))
return nil
}
func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
}