Json渲染
package mainimport ("net/http""github.com/gin-gonic/gin")func hellojson(c *gin.Context) {var hello struct {Id int //首字母必须大写,才可导出Msg string}hello.Id = 18hello.Msg = "hellojson"c.JSON(http.StatusOK, hello) //返回数据给浏览器}func main() {router := gin.Default() //定义默认路由router.GET("/json", hellojson) //访问/json,触发hellojson函数router.Run(":9090") //监听127.0.0.1:9090}
加xml渲染
要注意的是,xml比json多了结构体的定义,json是直接实例化。
package mainimport ("net/http""github.com/gin-gonic/gin")func hellojson(c *gin.Context) {var msg struct {Id int //首字母必须大写,才可导出Msg string}msg.Id = 1msg.Msg = "hellojson"c.JSON(http.StatusOK, msg) //返回数据给浏览器}func helloxml(c *gin.Context) {type msgxml struct { //和json不同,xml这里要定义结构体类型Id intMsg string}var msg msgxml //实例化结构体msg.Id = 2msg.Msg = "helloxml"c.XML(http.StatusOK, msg)}func main() {router := gin.Default() //定义默认路由router.GET("/json", hellojson) //访问/json,触发hellojson函数router.GET("/xml", helloxml) //访问/xml,触发helloxml函数router.Run(":9090") //监听127.0.0.1:9090}

其他的比如yaml,protobuf等,都是一样的,只是在返回的时候,选择不同的方法即可:c.YAML,c.ProtoBuf。
