两种绑定方法
Must bind
存在绑定错误,请求将被中止
Bind(Content-Type推断出使用哪种绑定器), BindJSON, BindXML, BindQuery, BindYAML
Should bind
存在绑定错误,则返回错误,开发人员可以正确处理请求和错误。
ShouldBind(Content-Type推断出使用哪种绑定器), ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML
/* binding:"required"修饰,并且在绑定时该字段的值为空,那么将返回一个错误。form是绑定查询参数
form:"user" 绑定查询参数
json:"user" 绑定json
xml:"user" 绑定xml
uri:"user" 绑定路径参数
header:"user" 绑定header
绑定Multipart/Urlencoded
File *multipart.FileHeader `form:"file"`
*/
type Login struct {
User string `form:"user" json:"user" xml:"user" binding:"required"`
Password string `form:"password" json:"password" xml:"password" binding:"required"`
}
//实例
var form Login
c.ShouldBind(&form)
一个接口接受不同格式的body
type formA struct {
Foo string `json:"foo" xml:"foo" binding:"required"`
}
type formB struct {
Bar string `json:"bar" xml:"bar" binding:"required"`
}
func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// This c.ShouldBind consumes c.Request.Body and it cannot be reused.
if errA := c.ShouldBind(&objA); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// Always an error is occurred by this because c.Request.Body is EOF now.
// 这样写会报错c.Request.Body is EOF,所以应该采用下面的方法
} else if errB := c.ShouldBind(&objB); errB == nil {
c.String(http.StatusOK, `the body should be formB`)
} else {
...
}
}
注意: c.Request.Body 只能被读取一次,二次读取会失败