跳转到内容

数据绑定

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 语法。

本节内容