跳到內容

渲染

Gin 支援以多種格式渲染回應,包括 JSON、XML、YAML、ProtoBuf、HTML 等。每個渲染方法都遵循相同的模式:在 *gin.Context 上呼叫方法,傳入 HTTP 狀態碼和要序列化的資料。Gin 會自動處理 content-type 標頭、序列化和寫入回應。

// All rendering methods share this pattern:
c.JSON(http.StatusOK, data) // application/json
c.XML(http.StatusOK, data) // application/xml
c.YAML(http.StatusOK, data) // application/x-yaml
c.TOML(http.StatusOK, data) // application/toml
c.ProtoBuf(http.StatusOK, data) // application/x-protobuf

你可以使用 Accept 標頭或查詢參數,從單一處理函式中以多種格式提供相同的資料:

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/user", func(c *gin.Context) {
user := gin.H{"name": "Lena", "role": "admin"}
switch c.Query("format") {
case "xml":
c.XML(http.StatusOK, user)
case "yaml":
c.YAML(http.StatusOK, user)
default:
c.JSON(http.StatusOK, user)
}
})
router.Run(":8080")
}

本節內容