背景:
通常情况下,JSON用它们的unicode实体替换特殊的HTML字符,例如<becomes\u003c。如果要按字面意思对这些字符进行编码,可以使用PureJSON代替。此功能在Go 1.6及更低版本中不可用。
代码:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// Serves unicode entities
r.GET("/json", func(c *gin.Context) {
c.JSON(200, gin.H{
"html": "<b>Hello, world!</b>",
})
})
// Serves literal characters
r.GET("/purejson", func(c *gin.Context) {
c.PureJSON(200, gin.H{
"html": "<b>Hello, world!</b>",
})
})
// listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
运行代码
客户端访问
->curl localhost:8080/json
{"html":"\u003cb\u003eHello, world!\u003c/b\u003e"}
->curl localhost:8080/purejson
{"html":"<b>Hello, world!</b>"}
->