背景:
通常情況下,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>"}
->