我是靠谱客的博主 喜悦钢铁侠,这篇文章主要介绍Gin 笔记(02)— 返回自定义格式(ascii json、自定义 json、安全的 json)1. 返回 ASCII json2. 自定义 json 结果3. 返回安全的 json,现在分享给大家,希望可以做个参考。

1. 返回 ASCII json

使用 c.AsciiJSON生成只有 ASCIIJSON,并转义非 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":"Gou8bedu8a00","tag":"u003cbru003e"}

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 笔记(02)— 返回自定义格式(ascii json、自定义 json、安全的 json)1. 返回 ASCII json2. 自定义 json 结果3. 返回安全的 json的全部内容,更多相关Gin内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(121)

评论列表共有 0 条评论

立即
投稿
返回
顶部