Gin XML/JSON/YAML/ProtoBuf 渲染

2022-03-29 15:56 更新
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) {
		// 你也可以使用一個結(jié)構(gòu)體
		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,
		}
		// 請注意,數(shù)據(jù)在響應(yīng)中變?yōu)槎M制數(shù)據(jù)
		// 將輸出被 protoexample.Test protobuf 序列化了的數(shù)據(jù)
		c.ProtoBuf(http.StatusOK, data)
	})

	// 監(jiān)聽并在 0.0.0.0:8080 上啟動服務(wù)
	r.Run(":8080")
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號