Gin 使用示例(二十六):PureJSON


通常,JSON 会通过 Unicode 编码特殊的 HTML 字符,比如将 < 替换成 \u003c,这样一来会影响可读性,如果你想要按照字面意义编码这些字符,可以使用 PureJSON 方法(适用于 Go 1.7 及以上版本):

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 进行测试:

-w625


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 使用示例(二十五):URL 路径中的参数

>> 下一篇: Gin 使用示例(二十七):获取查询字符串以及 POST 表单请求数据