컨텐츠로 건너뛰기

렌더링

Gin은 JSON, XML, YAML, ProtoBuf, HTML 등 여러 형식으로 응답을 렌더링하는 것을 지원합니다. 모든 렌더링 메서드는 동일한 패턴을 따릅니다: *gin.Context에서 HTTP 상태 코드와 직렬화할 데이터를 사용하여 메서드를 호출합니다. Gin은 content-type 헤더, 직렬화 및 응답 작성을 자동으로 처리합니다.

// 모든 렌더링 메서드는 이 패턴을 공유합니다:
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")
}

이 섹션의 내용