From e47a147c3bd0f3a605e0ef28ee2800a13153f186 Mon Sep 17 00:00:00 2001 From: astaxie Date: Tue, 6 Aug 2013 16:37:41 +0800 Subject: [PATCH] =?UTF-8?q?serverJson=20Supoort=20=E4=B8=AD=E6=96=87?= =?UTF-8?q?=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller.go | 5 ++++- utils.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/controller.go b/controller.go index aaec16ba..a563a56b 100644 --- a/controller.go +++ b/controller.go @@ -214,13 +214,16 @@ func (c *Controller) Abort(code string) { panic(code) } -func (c *Controller) ServeJson() { +func (c *Controller) ServeJson(encoding ...bool) { content, err := json.MarshalIndent(c.Data["json"], "", " ") if err != nil { http.Error(c.Ctx.ResponseWriter, err.Error(), http.StatusInternalServerError) return } c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=UTF-8") + if len(encoding) > 0 && encoding[0] == true { + content = []byte(stringsToJson(string(content))) + } c.writeToWriter(content) } diff --git a/utils.go b/utils.go index 5cc0707e..35f1aeb0 100644 --- a/utils.go +++ b/utils.go @@ -232,3 +232,17 @@ func ParseForm(form url.Values, obj interface{}) error { } return nil } + +func stringsToJson(str string) string { + rs := []rune(str) + jsons := "" + for _, r := range rs { + rint := int(r) + if rint < 128 { + jsons += string(r) + } else { + jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json + } + } + return jsons +}