5_gin日拱一足---各种数据格式的响应
gin框架日拱一足—各种数据格式的响应
响应数据的格式: json xml yaml struct 自定义…
分别调用*gin.Context的JSON,XML,YAML方法实现
其实最常使用的格式就是json
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//创建各种格式的响应: JSON YAML struct结构体 xml等等
//1.创建引擎
r := gin.Default()
// 响应JOSN --- 最长使用的一种格式
r.GET("/ResponseJSON",func(c *gin.Context){
c.JSON(http.StatusOK,gin.H{
"status": 200,
})
})
// 响应 xml
r.GET("/ResponseXML",func(c *gin.Context){
c.JSON(http.StatusOK,gin.H{"message": "abc"})
})
//响应结构体
r.GET("/ResponseStruct",func(c *gin.Context){
var a struct {
name string
age int
hobby string
}
a.name = "chenjunde"
a.age = 21
a.hobby = "golang"
c.JSON(http.StatusOK,a)
})
//响应yaml
r.GET("ResponseStruct",func(c *gin.Context){
c.YAML(http.StatusOK,gin.H{"status":"200"})
})
r.Run()
}