From a11ba9de3ba34c83aa1db07dcee360303c09b431 Mon Sep 17 00:00:00 2001 From: shine Date: Thu, 13 Oct 2016 18:04:49 +0800 Subject: [PATCH 1/2] response add jsonp support --- render.go | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/render.go b/render.go index 0cacb97..ee20aed 100644 --- a/render.go +++ b/render.go @@ -41,7 +41,7 @@ import ( "encoding/xml" "fmt" "html/template" - "io" + "io" "io/ioutil" "net/http" "os" @@ -62,6 +62,7 @@ const ( ContentHTML = "text/html" ContentXHTML = "application/xhtml+xml" ContentXML = "text/xml" + ContentScript = "application/javascript" defaultCharset = "UTF-8" ) @@ -81,6 +82,8 @@ var helperFuncs = template.FuncMap{ // Render is a service that can be injected into a Martini handler. Render provides functions for easily writing JSON and // HTML templates out to a http Response. type Render interface { + // JSONP writes the given status and JSON serialized version of the given value to the http.ResponseWriter. + JSONP(status int, v interface{}, callback string) // JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter. JSON(status int, v interface{}) // HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter. @@ -253,6 +256,38 @@ type renderer struct { compiledCharset string } +func (r *renderer) JSONP(status int, v interface{}, callback string) { + + var result []byte + var err error + if r.opt.IndentJSON { + result, err = json.MarshalIndent(v, "", " ") + } else { + result, err = json.Marshal(v) + } + if err != nil { + http.Error(r, err.Error(), 500) + return + } + + buf := bytes.NewBufferString(callback + "(") + + // json rendered fine, write out the result + r.Header().Set(ContentType, ContentScript+r.compiledCharset) + r.WriteHeader(status) + if len(r.opt.PrefixJSON) > 0 { + + buf.Write(r.opt.PrefixJSON) + buf.WriteString(")") + r.Write(buf.Bytes()) + } + + buf.Write(result) + buf.WriteString(")") + r.Write(buf.Bytes()) + +} + func (r *renderer) JSON(status int, v interface{}) { var result []byte var err error From 13954e87f3e01f433442a64a26595b69efc43763 Mon Sep 17 00:00:00 2001 From: shine Date: Thu, 13 Oct 2016 18:07:16 +0800 Subject: [PATCH 2/2] readme add jsonp example --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index d7be3a0..9b583bc 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,11 @@ func main() { r.Text(200, "hello, world") }) + // This will set the Content-Type header to "application/javascript; charset=ISO-8859-1" + m.Get("/jsonp", func(r render.Render) { + r.Text(200, map[string]interface{}{"hello": "world"},"callback") + }) + m.Run() }