feat: add SecureJSON func to prevent json hijacking

This commit is contained in:
Eason Lin
2017-07-08 01:21:30 +08:00
parent 0c3726b206
commit 75ed286c60
6 changed files with 101 additions and 9 deletions

View File

@ -5,6 +5,7 @@
package render
import (
"bytes"
"encoding/json"
"net/http"
)
@ -17,6 +18,13 @@ type IndentedJSON struct {
Data interface{}
}
type SecureJSON struct {
Prefix string
Data interface{}
}
type SecureJSONPrefix string
var jsonContentType = []string{"application/json; charset=utf-8"}
func (r JSON) Render(w http.ResponseWriter) (err error) {
@ -53,3 +61,21 @@ func (r IndentedJSON) Render(w http.ResponseWriter) error {
func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
}
func (r SecureJSON) Render(w http.ResponseWriter) error {
r.WriteContentType(w)
jsonBytes, err := json.Marshal(r.Data)
if err != nil {
return err
}
// if the jsonBytes is array values
if bytes.HasPrefix(jsonBytes, []byte("[")) && bytes.HasSuffix(jsonBytes, []byte("]")) {
w.Write([]byte(r.Prefix))
}
w.Write(jsonBytes)
return nil
}
func (r SecureJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
}