add json ASCII string render (#1358)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add a json render that rendering json as ASCII string
authored by Rex Lee(李俊) · committed by Bo-Yi Wu · parent d17a125 · Browse files · 5 files·+101 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+101 added−0 removed
- other:+101 added−0 removed
Provenance
- Commit
85221af- Tree
de01859- Author
Rex Lee(李俊) <duguying2008@gmail.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
d17a125
5 files changed+101 added−0 removed
modified:render/json.go+32 added
4 unmodified lines5 package render6 7 import (8 "bytes"9+ "fmt"10 "html/template"11 "net/http"12 13 "github.com/gin-gonic/gin/json"16 unmodified lines30 Callback string31 Data interface{}32 }33 34+type AsciiJSON struct {35+ Data interface{}36+}37+38 type SecureJSONPrefix string39 40 var jsonContentType = []string{"application/json; charset=utf-8"}41 var jsonpContentType = []string{"application/javascript; charset=utf-8"}42+var jsonAsciiContentType = []string{"application/json"}43 44 func (r JSON) Render(w http.ResponseWriter) (err error) {45 if err = WriteJSON(w, r.Data); err != nil {46 panic(err)70 unmodified lines117 118 func (r JsonpJSON) WriteContentType(w http.ResponseWriter) {119 writeContentType(w, jsonpContentType)120 }121+122+func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {123+ r.WriteContentType(w)124+ ret, err := json.Marshal(r.Data)125+ if err != nil {126+ return err127+ }128+129+ var buffer bytes.Buffer130+ for _, r := range string(ret) {131+ cvt := ""132+ if r < 128 {133+ cvt = string(r)134+ } else {135+ cvt = fmt.Sprintf("\\u%04x", int64(r))136+ }137+ buffer.WriteString(cvt)138+ }139+140+ w.Write(buffer.Bytes())141+ return nil142+}143+144+func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {145+ writeContentType(w, jsonAsciiContentType)146+}modified:render/render_test.go+29 added
165 unmodified lines166 err := (JsonpJSON{"x", data}).Render(w)167 assert.Error(t, err)168 }169 170+func TestRenderAsciiJSON(t *testing.T) {171+ w1 := httptest.NewRecorder()172+ data1 := map[string]interface{}{173+ "lang": "GO语言",174+ "tag": "<br>",175+ }176+177+ err := (AsciiJSON{data1}).Render(w1)178+179+ assert.NoError(t, err)180+ assert.Equal(t, "{\"lang\":\"GO\\u8bed\\u8a00\",\"tag\":\"\\u003cbr\\u003e\"}", w1.Body.String())181+ assert.Equal(t, "application/json", w1.Header().Get("Content-Type"))182+183+ w2 := httptest.NewRecorder()184+ data2 := float64(3.1415926)185+186+ err = (AsciiJSON{data2}).Render(w2)187+ assert.NoError(t, err)188+ assert.Equal(t, "3.1415926", w2.Body.String())189+}190+191+func TestRenderAsciiJSONFail(t *testing.T) {192+ w := httptest.NewRecorder()193+ data := make(chan int)194+195+ // json: unsupported type: chan int196+ assert.Error(t, (AsciiJSON{data}).Render(w))197+}198+199 type xmlmap map[string]interface{}200 201 // Allows type H to be used with xml.Marshal202 func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {236 unmodified linesmodified:context_test.go+11 added
684 unmodified lines685 assert.Empty(t, w.Body.String())686 assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))687 }688 689+func TestContextRenderNoContentAsciiJSON(t *testing.T) {690+ w := httptest.NewRecorder()691+ c, _ := CreateTestContext(w)692+693+ c.AsciiJSON(http.StatusNoContent, []string{"lang", "Go语言"})694+695+ assert.Equal(t, http.StatusNoContent, w.Code)696+ assert.Empty(t, w.Body.String())697+ assert.Equal(t, "application/json", w.HeaderMap.Get("Content-Type"))698+}699+700 // Tests that the response executes the templates701 // and responds with Content-Type set to text/html702 func TestContextRenderHTML(t *testing.T) {703 w := httptest.NewRecorder()800 unmodified linesmodified:context.go+6 added
702 unmodified lines703 func (c *Context) JSON(code int, obj interface{}) {704 c.Render(code, render.JSON{Data: obj})705 }706 707+// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.708+// It also sets the Content-Type as "application/json".709+func (c *Context) AsciiJSON(code int, obj interface{}) {710+ c.Render(code, render.AsciiJSON{Data: obj})711+}712+713 // XML serializes the given struct as XML into the response body.714 // It also sets the Content-Type as "application/xml".715 func (c *Context) XML(code int, obj interface{}) {716 c.Render(code, render.XML{Data: obj})165 unmodified linesmodified:README.md+23 added
898 unmodified lines899 r.Run(":8080")900 }901 ```902 903+#### AsciiJSON904+905+Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII chracters.906+907+```go908+func main() {909+ r := gin.Default()910+911+ r.GET("/someJSON", func(c *gin.Context) {912+ data := map[string]interface{}{913+ "lang": "GO语言",914+ "tag": "<br>",915+ }916+917+ // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}918+ c.AsciiJSON(http.StatusOK, data)919+ })920+921+ // Listen and serve on 0.0.0.0:8080922+ r.Run(":8080")923+}924+```925+926 ### Serving static files927 928 ```go929 func main() {861 unmodified lines