跳转到内容

渲染

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")
}

本节内容