数据绑定介绍
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
,ShouldBindXML
,ShouldBindQuery
,ShouldBindYAML
- Behavior
- 这些方法属于
ShouldBindWith
的具体调用。 如果发生绑定错误,Gin 会返回错误并由开发者处理错误和请求。