Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
37 changes: 36 additions & 1 deletion render.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import (
"encoding/xml"
"fmt"
"html/template"
"io"
"io"
"io/ioutil"
"net/http"
"os"
Expand All @@ -62,6 +62,7 @@ const (
ContentHTML = "text/html"
ContentXHTML = "application/xhtml+xml"
ContentXML = "text/xml"
ContentScript = "application/javascript"
defaultCharset = "UTF-8"
)

Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down