Gin ShouldBind 和 Bind 的区别

2,039 阅读1分钟

BindJSON()

返回错误,并在header里面写400的状态码

// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
func (c *Context) BindJSON(obj interface{}) error {
	return c.MustBindWith(obj, binding.JSON)
}
// MustBindWith binds the passed struct pointer using the specified binding engine.
// It will abort the request with HTTP 400 if any error ocurrs.
// See the binding package.
func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) {
	if err = c.ShouldBindWith(obj, b); err != nil {
		c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)
	}

	return
}

ShouldBindJSON()

只会返回错误信息,不会往header里面写400的错误状态码

// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
func (c *Context) ShouldBindJSON(obj interface{}) error {
	return c.ShouldBindWith(obj, binding.JSON)
}
// ShouldBindWith binds the passed struct pointer using the specified binding engine.
// See the binding package.
func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
	return b.Bind(c.Request, obj)
}

ShouldBindWith,根据b的类型去绑定json,query,去绑定

func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
	return b.Bind(c.Request, obj)
}

如何选择使用

gin提供了灵活的bind解析参数的方法供你选择

  1. 解析错误回在header中写一个400的状态码
	//内部根据Content-Type去解析
	c.Bind(obj interface{})
	//内部替你传递了一个binding.JSON,对象去解析
	c.BindJSON(obj interface{})
	//解析哪一种绑定的类型,根据你的选择
	c.BindWith(obj interface{}, b binding.Binding)

  1. 解析错误直接返回,至于要给客户端返回什么错误状态码有你决定
	//内部根据Content-Type去解析
	c.ShouldBind(obj interface{})
	//内部替你传递了一个binding.JSON,对象去解析
	c.ShouldBindJSON(obj interface{})
	//解析哪一种绑定的类型,根据你的选择
	c.ShouldBindWith(obj interface{}, b binding.Binding)

  1. Shouldxxx和bindxxx区别就是bindxxx会在head中添加400的返回信息,而Shouldxxx不会