教程 > gin 教程 > 阅读:45

gin xml/json/yaml/protobuf 渲染——迹忆客-ag捕鱼王app官网

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})
    })
    r.get("/someprotobuf", func(c *gin.context) {
        reps := []int64{int64(1), int64(2)}
        label := "test"
        // protobuf 的具体定义写在 testdata/protoexample 文件中。
        data := &protoexample.test{
            label: &label,
            reps:  reps,
        }
        // 请注意,数据在响应中变为二进制数据
        // 将输出被 protoexample.test protobuf 序列化了的数据
        c.protobuf(http.statusok, data)
    })
    // 监听并在 0.0.0.0:8080 上启动服务
    r.run(":8080")
}

查看笔记

扫码一下
查看教程更方便
网站地图