gin中XML/JSON/YAML/ProtoBuf 渲染

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/testdata/protoexample"
)

func main() {
	router := gin.Default()
	router.GET("/some_json", func(c *gin.Context) {
		names := []string{"zhangsan", "李四", "wangwu"}
		c.JSON(200, names)
	})
	router.GET("/more_json", func(c *gin.Context) {
		var msg struct {
			Name string `json:"user"`
			Message string
			Number int
		}
		msg.Name, msg.Message, msg.Number = "lisi", "哈哈", 15
		c.JSON(200, msg)
	})
	router.GET("/some_xml", func(context *gin.Context) {
		context.XML(200, gin.H{"status": "XML", "Message": "hey"})
	})
	router.GET("/some_yaml", func(context *gin.Context) {
		context.YAML(200, gin.H{"status": "YAML", "message": "ha"})
	})
	router.GET("/some_protobuf", func(context *gin.Context) {
		resp := []int64{int64(1), int64(2)}
		label := "test"
		// protobuf 的具体定义写在 testdata/protoexample 文件中。
		data := &protoexample.Test{Label: &label, Reps: resp}
		// 请注意,数据在响应中变为二进制数据
		// 将输出被 protoexample.Test protobuf 序列化了的数据
		context.ProtoBuf(200, data)
	})

	router.Run()
}

  

posted @ 2021-10-20 15:39  专职  阅读(199)  评论(0编辑  收藏  举报