跳到內容

資料綁定

Gin 提供了強大的綁定系統,可以將請求資料解析到 Go 結構體中並自動進行驗證。你不需要手動呼叫 c.PostForm() 或讀取 c.Request.Body,只需定義帶有標籤的結構體,讓 Gin 來完成工作。

Bind 與 ShouldBind

Gin 提供兩類綁定方法:

方法錯誤時使用時機
c.Bindc.BindJSON自動呼叫 c.AbortWithError(400, err)你希望 Gin 處理錯誤回應
c.ShouldBindc.ShouldBindJSON回傳錯誤讓你自行處理你想要自訂錯誤回應

在大多數情況下,建議使用 ShouldBind 以獲得更多的錯誤處理控制權。

快速範例

type LoginForm struct {
User string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/login", func(c *gin.Context) {
var form LoginForm
// ShouldBind checks Content-Type to select a binding engine automatically
if err := c.ShouldBind(&form); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "logged in"})
})
router.Run(":8080")
}

支援的格式

Gin 可以從多種來源綁定資料:JSONXMLYAMLTOML表單資料(URL 編碼和 multipart)、查詢字串URI 參數標頭。使用對應的結構體標籤(jsonxmlyamlformuriheader)來映射欄位。驗證規則放在 binding 標籤中,使用 go-playground/validator 語法。

本節內容