1 // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2 // Use of this source code is governed by a MIT style
3 // license that can be found in the LICENSE file.
13 "github.com/gin-gonic/gin/json"
20 type IndentedJSON struct {
24 type SecureJSON struct {
29 type JsonpJSON struct {
34 type AsciiJSON struct {
38 type SecureJSONPrefix string
40 var jsonContentType = []string{"application/json; charset=utf-8"}
41 var jsonpContentType = []string{"application/javascript; charset=utf-8"}
42 var jsonAsciiContentType = []string{"application/json"}
44 func (r JSON) Render(w http.ResponseWriter) (err error) {
45 if err = WriteJSON(w, r.Data); err != nil {
51 func (r JSON) WriteContentType(w http.ResponseWriter) {
52 writeContentType(w, jsonContentType)
55 func WriteJSON(w http.ResponseWriter, obj interface{}) error {
56 writeContentType(w, jsonContentType)
57 jsonBytes, err := json.Marshal(obj)
65 func (r IndentedJSON) Render(w http.ResponseWriter) error {
67 jsonBytes, err := json.MarshalIndent(r.Data, "", " ")
75 func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {
76 writeContentType(w, jsonContentType)
79 func (r SecureJSON) Render(w http.ResponseWriter) error {
81 jsonBytes, err := json.Marshal(r.Data)
85 // if the jsonBytes is array values
86 if bytes.HasPrefix(jsonBytes, []byte("[")) && bytes.HasSuffix(jsonBytes, []byte("]")) {
87 w.Write([]byte(r.Prefix))
93 func (r SecureJSON) WriteContentType(w http.ResponseWriter) {
94 writeContentType(w, jsonContentType)
97 func (r JsonpJSON) Render(w http.ResponseWriter) (err error) {
99 ret, err := json.Marshal(r.Data)
104 if r.Callback == "" {
109 callback := template.JSEscapeString(r.Callback)
110 w.Write([]byte(callback))
118 func (r JsonpJSON) WriteContentType(w http.ResponseWriter) {
119 writeContentType(w, jsonpContentType)
122 func (r AsciiJSON) Render(w http.ResponseWriter) (err error) {
123 r.WriteContentType(w)
124 ret, err := json.Marshal(r.Data)
129 var buffer bytes.Buffer
130 for _, r := range string(ret) {
135 cvt = fmt.Sprintf("\\u%04x", int64(r))
137 buffer.WriteString(cvt)
140 w.Write(buffer.Bytes())
144 func (r AsciiJSON) WriteContentType(w http.ResponseWriter) {
145 writeContentType(w, jsonAsciiContentType)