쿼리 문자열 또는 POST 데이터 바인딩
ShouldBind는 HTTP 메서드와 Content-Type 헤더에 따라 자동으로 바인딩 엔진을 선택합니다:
- GET 요청의 경우 쿼리 문자열 바인딩(
form태그)을 사용합니다. - POST/PUT 요청의 경우
Content-Type을 확인하여application/json에는 JSON 바인딩,application/xml에는 XML 바인딩,application/x-www-form-urlencoded또는multipart/form-data에는 폼 바인딩을 사용합니다.
이는 단일 핸들러가 수동 소스 선택 없이 쿼리 문자열과 요청 바디 모두에서 데이터를 수신할 수 있음을 의미합니다.
package main
import ( "log" "net/http" "time"
"github.com/gin-gonic/gin")
type Person struct { Name string `form:"name"` Address string `form:"address"` Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`}
func main() { route := gin.Default() route.GET("/testing", startPage) route.POST("/testing", startPage) route.Run(":8085")}
func startPage(c *gin.Context) { var person Person if err := c.ShouldBind(&person); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return }
log.Printf("Name: %s, Address: %s, Birthday: %s\n", person.Name, person.Address, person.Birthday) c.JSON(http.StatusOK, gin.H{ "name": person.Name, "address": person.Address, "birthday": person.Birthday, })}테스트
# GET with query string parameterscurl "http://localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"# Output: {"address":"xyz","birthday":"1992-03-15T00:00:00Z","name":"appleboy"}
# POST with form datacurl -X POST http://localhost:8085/testing \ -d "name=appleboy&address=xyz&birthday=1992-03-15"# Output: {"address":"xyz","birthday":"1992-03-15T00:00:00Z","name":"appleboy"}
# POST with JSON bodycurl -X POST http://localhost:8085/testing \ -H "Content-Type: application/json" \ -d '{"name":"appleboy","address":"xyz","birthday":"1992-03-15"}'# Output: {"address":"xyz","birthday":"1992-03-15T00:00:00Z","name":"appleboy"}