This commit is contained in:
Rex Lee(李俊) 2018-05-16 16:57:59 +08:00
parent f71e5432df
commit 98acb016cf
2 changed files with 33 additions and 4 deletions

View File

@ -6,9 +6,9 @@ package render
import (
"bytes"
"fmt"
"html/template"
"net/http"
"strconv"
"github.com/gin-gonic/gin/json"
)
@ -127,12 +127,12 @@ func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {
}
result := ""
for _, r := range ret {
for _, r := range string(ret) {
cvt := ""
if r < 128 {
cvt = string(r)
} else {
cvt = `\u` + strconv.FormatInt(int64(r), 16)
cvt = fmt.Sprintf("\\u%04x", int64(r))
}
result = result + cvt
}
@ -142,5 +142,5 @@ func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {
}
func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
writeContentType(w, jsonAsciiContentType)
}

View File

@ -167,6 +167,35 @@ func TestRenderJsonpJSONFail(t *testing.T) {
assert.Error(t, err)
}
func TestRenderAsciiJSON(t *testing.T) {
w1 := httptest.NewRecorder()
data1 := map[string]interface{}{
"lang": "GO语言",
"tag": "<br>",
}
err := (AsciiJSON{data1}).Render(w1)
assert.NoError(t, err)
assert.Equal(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String())
assert.Equal(t, "application/json", w1.Header().Get("Content-Type"))
w2 := httptest.NewRecorder()
data2 := float64(3.1415926)
err = (AsciiJSON{data2}).Render(w2)
assert.NoError(t, err)
assert.Equal(t, "3.1415926", w2.Body.String())
}
func TestRenderAsciiJSONFail(t *testing.T) {
w := httptest.NewRecorder()
data := make(chan int)
// json: unsupported type: chan int
assert.Error(t, (AsciiJSON{data}).Render(w))
}
type xmlmap map[string]interface{}
// Allows type H to be used with xml.Marshal