gin的BindJSON和ShouldBindJSON,ShouldBindWith的区别

gin的BindJSON和ShouldBindJSON,ShouldBindWith的区别

BindJSON和ShouldBindJSON,ShouldBindWith的区别

  • 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不会
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值