Gin 笔记(02)— 返回自定义格式(ascii json、自定义 json、安全的 json)

该博客介绍了如何使用Gin框架返回ASCII JSON,自定义JSON响应格式以及确保JSON安全的方法。通过c.AsciiJSON可以转义非ASCII字符,SendResponse函数展示了自定义返回结构体,而c.SecureJSON则用于防止JSON劫持,它会在数组值前默认添加'while(1)'以增加安全性。
摘要由CSDN通过智能技术生成

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":"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")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wohu007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值