1. 返回 ASCII json
使用 c.AsciiJSON
生成只有 ASCII
的 JSON
,并转义非 ASCII
字符。
func asciiResponse(c *gin.Context) {
data := map[string]interface{}{
"lang": "Go语言",
"tag": "<br>",
}
c.AsciiJSON(http.StatusOK, data)
}
func main() {
r := gin.Default()
r.GET("/ascii_json", asciiResponse)
r.Run() // listen and serve on 0.0.0.0:8080
}
输出结果:
$ curl http://127.0.0.1:8080/ascii_json
{"lang":"Go\u8bed\u8a00","tag":"\u003cbr\u003e"}
2. 自定义 json 结果
如果要返回指定的格式,可以通过统一的返回函数 SendResponse
来格式化返回的结果。
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func customResponse(code int, message string, data interface{}) Response {
res := Response{
Code: code,
Message: message,
Data: data,
}
return res
}
func SendResponse(c *gin.Context) {
code := 200
message := "response message"
data := "data"
res := customResponse(code, message, data)
// always return http.StatusOK
c.JSON(http.StatusOK, res)
}
func main() {
r := gin.Default()
r.GET("/send", SendResponse)
r.Run() // listen and serve on 0.0.0.0:8080
}
运行结果:
$ curl http://127.0.0.1:8080/send
{"code":200,"message":"response message","data":"data"}
3. 返回安全的 json
使用 SecureJSON
来防止 json
被劫持。如果给定的结构是数组值,默认将 while(1)
添加到响应体中。
func main() {
r := gin.Default()
// You can also use your own secure json prefix
// r.SecureJsonPrefix(")]}',\n")
r.GET("/someJSON", func(c *gin.Context) {
names := []string{"lena", "austin", "foo"}
// Will output : while(1);["lena","austin","foo"]
c.SecureJSON(http.StatusOK, names)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}