XML, JSON 和 YAML 渲染
func main() {
r := gin.Default()
// gin.H 是一个 map[string]interface{} 的快捷方式
r.GET("/someJSON", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/moreJSON", func(c *gin.Context) {
// 你也可以使用一个结构
var msg struct {
Name string `json:"user"`
Message string
Number int
}
msg.Name = "Lena"
msg.Message = "hey"
msg.Number = 123
// 注意 msg.Name 在 JSON 中会变成 "user"
// 将会输出: {"user": "Lena", "Message": "hey", "Number": 123}
c.JSON(http.StatusOK, msg)
})
r.GET("/someXML", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
// 监听并服务于 0.0.0.0:8080
r.Run(":8080")
}
SecureJSON
使用 SecureJSON 来防止 json 劫持。如果给定的结构体是数组值,默认预置 "while(1),"
到 response body 。
func main() {
r := gin.Default()
// 你也可以使用自己的安装 json 前缀
// r.SecureJsonPrefix(")]}',\n")
r.GET("/someJSON", func(c *gin.Context) {
names := []string{"lena", "austin", "foo"}
// 将会输出 : while(1);["lena","austin","foo"]
c.SecureJSON(http.StatusOK, names)
})
// 监听并服务于 0.0.0.0:8080
r.Run(":8080")
}
JSONP
在不同的域中使用 JSONP 从一个服务器请求数据。如果请求参数中存在 callback,添加 callback 到 response body 。
func main() {
r := gin.Default()
r.GET("/JSONP?callback=x", func(c *gin.Context) {
data := map[string]interface{}{
"foo": "bar",
}
//callback 是 x
// 将会输出 : x({\"foo\":\"bar\"})
c.JSONP(http.StatusOK, data)
})
// 监听并服务于 0.0.0.0:8080
r.Run(":8080")
}