Gin 绑定参数

2年前 (2022) 程序员胖胖胖虎阿
143 0 0

Gin 提供了两类绑定方法:Must bind 和 Should bind

Must bind 的方法有 Bind,BindJSON,BindXML,BindQuery,BindYAML,这些方法属于 BindWith 的具体调用。

Must bind 如果发生绑定错误,则请求终止,并触发 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。

Should bind的方法有 ShouldBind,ShouldBindJSON,ShouldBindXML,ShouldBindQuery,ShouldBindYAML,这些方法属于 ShouldBindWith 的具体调用。

Should bind 如果发生绑定错误,Gin 会返回错误并由开发者处理错误和请求。
使用 Bind 方法时,Gin 会尝试根据 Content-Type 推断如何绑定。如果你明确知道要绑定什么,可以使用 MustBindWith 或 ShouldBindWith。

参考:
https://icode.best/i/97680946...

版权声明:程序员胖胖胖虎阿 发表于 2022年10月24日 上午4:48。
转载请注明:Gin 绑定参数 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...