常用返回数据格式: XML, JSON, YAML and ProtoBuf
func main() {
r := gin.Default()
// gin.H is a shortcut for 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) {
// You also can use a struct
var msg struct {
Name string `json:"user"`
Message string
Number int
}
msg.Name = "Lena"
msg.Message = "hey"
msg.Number = 123
// Note that msg.Name becomes "user" in the JSON
// Will output : {"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})
})
r.GET("/someProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
// The specific definition of protobuf is written in the testdata/protoexample file.
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
// Note that data becomes binary data in the response
// Will output protoexample.Test protobuf serialized data
c.ProtoBuf(http.StatusOK, data)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
SecureJSON
使用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")
}
JSONP
使用JSONP从不同域中的服务器请求数据。如果存在查询参数回调,则向响应正文添加回调。
func main() {
r := gin.Default()
r.GET("/JSONP", func(c *gin.Context) {
data := gin.H{
"foo": "bar",
}
//callback is x
// Will output : x({"foo":"bar"})
c.JSONP(http.StatusOK, data)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
// client
// curl http://127.0.0.1:8080/JSONP?callback=x
}
AsciiJSON
使用ASCII JSON生成具有转义非ASCII字符的仅ASCII JSON。
func main() {
r := gin.Default()
r.GET("/someJSON", func(c *gin.Context) {
data := gin.H{
"lang": "GO语言",
"tag": "<br>",
}
// will output : {"lang":"GOu8bedu8a00","tag":" bru003e"}
c.AsciiJSON(http.StatusOK, data)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
PureJSON
通常,JSON会将特殊的HTML字符替换为它们的unicode实体,例如 <变成 u003c。如果要按字面意思对这些字符进行编码,可以改用PureJSON。 此功能在Go 1.6及更低版本中不可用。
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")
}