add json ASCII string render (#1358)

add a json render that rendering json as ASCII string
This commit is contained in:
Rex Lee(李俊)
2018-07-03 17:17:08 +08:00
committed by Bo-Yi Wu
parent d17a12591f
commit 85221af84c
5 changed files with 101 additions and 0 deletions

View File

@ -6,6 +6,7 @@ package render
import (
"bytes"
"fmt"
"html/template"
"net/http"
@ -30,10 +31,15 @@ type JsonpJSON struct {
Data interface{}
}
type AsciiJSON struct {
Data interface{}
}
type SecureJSONPrefix string
var jsonContentType = []string{"application/json; 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) {
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) {
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
}
var buffer bytes.Buffer
for _, r := range string(ret) {
cvt := ""
if r < 128 {
cvt = string(r)
} else {
cvt = fmt.Sprintf("\\u%04x", int64(r))
}
buffer.WriteString(cvt)
}
w.Write(buffer.Bytes())
return nil
}
func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonAsciiContentType)
}