模型绑定和验证

    Gin使用 go-playground/validator.v8 进行验证。 查看标签用法的全部.

    Gin提供了两类绑定方法:

    • Type - Must bind
      • Methods - Bind, BindJSON, BindXML, BindQuery, BindYAML
      • Behavior - 这些方法属于 MustBindWith 的具体调用。 如果发生绑定错误,则请求终止,并触发 c.AbortWithError(400, err).SetType(ErrorTypeBind)。响应状态码被设置为 400 并且 Content-Type 被设置为 text/plain; charset=utf-8。 如果您在此之后尝试设置响应状态码,Gin会输出日志 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422。 如果您希望更好地控制绑定,考虑使用 ShouldBind 等效方法。
    • Type - Should bind
      • Methods - ShouldBind, ShouldBindJSON, , ShouldBindQuery, ShouldBindYAML
      • Behavior - 这些方法属于 ShouldBindWith 的具体调用。 如果发生绑定错误,Gin 会返回错误并由开发者处理错误和请求。使用 Bind 方法时,Gin 会尝试根据 Content-Type 推断如何绑定。 如果你明确知道要绑定什么,可以使用 MustBindWithShouldBindWith

    示例请求

    1. http://localhost:8080/loginJSON \
    2. -H 'content-type: application/json' \
    3. -d '{ "user": "manu" }'
    4. > POST /loginJSON HTTP/1.1
    5. > Host: localhost:8080
    6. > User-Agent: curl/7.51.0
    7. > content-type: application/json
    8. >
    9. * upload completely sent off: 18 out of 18 bytes
    10. < HTTP/1.1 400 Bad Request
    11. < Content-Type: application/json; charset=utf-8
    12. < Date: Fri, 04 Aug 2017 03:51:31 GMT
    13. < Content-Length: 100
    14. <
    15. {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}

    忽略验证

    使用上述的 curl 命令运行上面的示例时会返回错误。 因为示例中 Password 使用了 binding:"required"。 如果 使用 binding:"-", 再次运行上面的示例就不会返回错误。