1.绑定的方法
在Gin中,提供了两套绑定参数到结构体的方法
- 一套是"ShouldBind"开头的方法,底层使用ShouldBindWith()方法处理,特点是如果发生绑定错误,直接返回错误,由程序员来处理该错误。
func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {
return b.Bind(c.Request, obj)
}
- 另外一套"Bind"开头的方法,底层使用的是MustBindWith,而MustBindWith直接使用了ShouldBindWith()去绑定。特点是如果发生绑定错误,请求会被终止,自行设置响应状态码为400,请求头Content-Type被设置为text/plain; charset=utf-8,不能再去返回错误的状态码。
func (c *Context) MustBindWith(obj any, b binding.Binding) error {
if err := c.ShouldBindWith(obj, b); err != nil {
c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //不想要:errcheck
return err
}
return nil
}
- 当绑定错误发生的时候,如果后续依旧设置新的响应代码,会触发警告,状态码被覆盖。
- 特别的,Bind(obj any) 会根据Content-type自动选择对应类型的绑定器
- BindWith(obj any, b binding.Binding) 也只调用MustBindWith(),只不过调用前增加了一个日志提示。
2.使用方式
- ShouldBind 自动根据content/type确定绑定参数的类型,能绑定query,post,html参数
GET或者POST请求,同时具有Query参数
绑定GET请求时,优先处理Query参数,
绑定POST请求时,优先处理Postform参数,
- ShouldBindJSON 绑定JSON参数
- ShouldBindUri 绑定path参数
- ShouldBindQuery 绑定query参数
- ShouldBindWith 自动定义绑定对象去绑定参数
MustBind系列类似上边。