Skip to content

Rendering

Gin supports rendering responses in multiple formats including JSON, XML, YAML, ProtoBuf, HTML, and more. Every rendering method follows the same pattern: call a method on *gin.Context with an HTTP status code and the data to serialize. Gin handles content-type headers, serialization, and writing the response automatically.

// 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

You can use the Accept header or a query parameter to serve the same data in multiple formats from a single handler:

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

In this section