介绍
本文主要介绍 gin框架中的 SecureJSON,使用 SecureJSON 防止 json 劫持。如果给定的结构是数组值,则默认预置 “while(1),” 到响应体。
案例
源码:
package main
import "github.com/gin-gonic/gin"
type User struct {
Name string
Age int
}
func main() {
r := gin.Default()
r.GET("/secureJson/exp01", func(c *gin.Context) {
names := []string{"item01", "item02", "item03"}
c.SecureJSON(200, names)
})
r.GET("/secureJson/exp02", func(c *gin.Context) {
names := User{"bob", 18}
c.SecureJSON(200, names)
})
r.Run(":8080")
}
测试:
$ curl -XGET http://127.0.0.01:8080/secureJson/exp01
while(1);["item01","item02","item03"]
$ curl -XGET http://127.0.0.01:8080/secureJson/exp02
{"Name":"bob","Age":18}