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")
}
该博客介绍了如何使用Gin框架返回ASCII JSON,自定义JSON响应格式以及确保JSON安全的方法。通过c.AsciiJSON可以转义非ASCII字符,SendResponse函数展示了自定义返回结构体,而c.SecureJSON则用于防止JSON劫持,它会在数组值前默认添加'while(1)'以增加安全性。
2347

被折叠的 条评论
为什么被折叠?



