mirror of
https://github.com/gin-gonic/gin.git
synced 2025-08-06 15:50:30 +08:00
feat: add SecureJSON func to prevent json hijacking
This commit is contained in:
@ -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)
|
||||
}
|
||||
|
Reference in New Issue
Block a user