Gin 如何渲染和响应不同的格式:XML, JSON, YAML, TOML 和 ProtoBuf?

76 min read

在Gin中,可以使用不同的库来渲染和响应不同的数据格式。以下是几种流行的格式和相应的库:

XML:使用Go内置的“encoding/xml”包来渲染XML格式数据,并使用Gin内置的“xml”渲染器:

type Person struct {
    Name string `xml:"name"`
    Age int `xml:"age"`
}

func main() {
    router := gin.Default()

    router.GET("/person", func(c *gin.Context) {
        person := Person{"Alice", 25}
        c.XML(http.StatusOK, person)
    })

    router.Run(":8080")
}

JSON:使用Go内置的“encoding/json”包来渲染JSON格式数据,并使用Gin内置的“json”渲染器:

type Person struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

func main() {
    router := gin.Default()

    router.GET("/person", func(c *gin.Context) {
        person := Person{"Alice", 25}
        c.JSON(http.StatusOK, person)
    })

    router.Run(":8080")
}

YAML:使用“gopkg.in/yaml.v2”包来渲染YAML格式数据,并使用Gin内置的“yaml”渲染器:

type Person struct {
    Name string `yaml:"name"`
    Age int `yaml:"age"`
}

func main() {
    router := gin.Default()

    router.GET("/person", func(c *gin.Context) {
        person := Person{"Alice", 25}
        c.YAML(http.StatusOK, person)
    })

    router.Run(":8080")
}

TOML:使用“github.com/BurntSushi/toml”包来渲染TOML格式数据,并自定义响应:

type Person struct {
    Name string `toml:"name"`
    Age int `toml:"age"`
}

func main() {
    router := gin.Default()

    router.GET("/person", func(c *gin.Context) {
        person := Person{"Alice", 25}
        tomlData, err := toml.Marshal(person)
        if err != nil {
            c.String(http.StatusInternalServerError, "Error: %v", err)
        } else {
            c.Data(http.StatusOK, "text/plain; charset=utf-8", tomlData)
        }
    })

    router.Run(":8080")
}

ProtoBuf:使用Google的“protobuf”包来渲染ProtoBuf格式数据,并自定义响应:

import (
    "net/http"

    "github.com/gin-gonic/gin"
    pb "github.com/golang/protobuf/proto"
)

type Person struct {
    Name string
    Age int32
}

func main() {
    router := gin.Default()

    router.GET("/person", func(c *gin.Context) {
        person := Person{"Alice", 25}
        protoData, err := pb.Marshal(&person)
        if err != nil {
            c.String(http.StatusInternalServerError, "Error: %v", err)
        } else {
            c.Data(http.StatusOK, "application/octet-stream", protoData)
        }
    })

    router.Run(":8080")
}