两种绑定方法

Must bind

存在绑定错误,请求将被中止
Bind(Content-Type推断出使用哪种绑定器), BindJSON, BindXML, BindQuery, BindYAML

Should bind

存在绑定错误,则返回错误,开发人员可以正确处理请求和错误。
ShouldBind(Content-Type推断出使用哪种绑定器), ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML

  1. /* binding:"required"修饰,并且在绑定时该字段的值为空,那么将返回一个错误。form是绑定查询参数
  2. form:"user" 绑定查询参数
  3. json:"user" 绑定json
  4. xml:"user" 绑定xml
  5. uri:"user" 绑定路径参数
  6. header:"user" 绑定header
  7. 绑定Multipart/Urlencoded
  8. File *multipart.FileHeader `form:"file"`
  9. */
  10. type Login struct {
  11. User string `form:"user" json:"user" xml:"user" binding:"required"`
  12. Password string `form:"password" json:"password" xml:"password" binding:"required"`
  13. }
  14. //实例
  15. var form Login
  16. c.ShouldBind(&form)

一个接口接受不同格式的body

  1. type formA struct {
  2. Foo string `json:"foo" xml:"foo" binding:"required"`
  3. }
  4. type formB struct {
  5. Bar string `json:"bar" xml:"bar" binding:"required"`
  6. }
  7. func SomeHandler(c *gin.Context) {
  8. objA := formA{}
  9. objB := formB{}
  10. // This c.ShouldBind consumes c.Request.Body and it cannot be reused.
  11. if errA := c.ShouldBind(&objA); errA == nil {
  12. c.String(http.StatusOK, `the body should be formA`)
  13. // Always an error is occurred by this because c.Request.Body is EOF now.
  14. // 这样写会报错c.Request.Body is EOF,所以应该采用下面的方法
  15. } else if errB := c.ShouldBind(&objB); errB == nil {
  16. c.String(http.StatusOK, `the body should be formB`)
  17. } else {
  18. ...
  19. }
  20. }

注意: c.Request.Body 只能被读取一次,二次读取会失败