Gin 学习之绑定参数

时间:2022-07-24
本文章向大家介绍Gin 学习之绑定参数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

01

概念

要将请求体绑定到结构体中,需要使用模型绑定。Gin 目前支持JSON、XML、YAML和标准表单值的绑定(foo=bar&boo=baz)。

使用时,结构体字段首字母必须大写。需要在要绑定的所有字段上,设置相应的tag。例如,使用 JSON 绑定时,设置字段标签为 json:"fieldname"。你也可以指定必须绑定的字段。如果一个字段的 tag 加上了 binding:"required",但绑定时是空值, Gin 会报错。Gin 使用 go-playground/validator.v8 进行验证。

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。

如果您希望更好地控制绑定,考虑使用 ShouldBind 等效方法。如果对 Must bind 的方法感兴趣,可以查阅文档或阅读 Gin 源码,本文我们主要介绍 Should bind 的方法。

本文示例代码需要使用到的自定义结构体类型。

type user struct {  Name string `form:"username" json:"username" xml:"username" uri:"username"`  Age  int    `form:"age" json:"age" xml:"age" uri:"age"`}
type student struct {  UserInfo user `form:"userinfo"`  Score    int  `form:"score" json:"score" xml:"score" uri:"score"`}

02

ShouldBind

func (*gin.Context).ShouldBind(obj interface{}) error

ShouldBind 支持绑定 urlencoded form 和 multipart form。

如果是 `GET` 请求,只使用 `Form` 绑定引擎(`query`)。

如果是 `POST` 请求,首先检查 `content-type` 是否为 `JSON` 或 `XML`,然后再使用 `Form`(`form-data`)。

绑定到结构体

绑定到嵌套结构体

03

ShouldBindJSON

func (*gin.Context).ShouldBindJSON(obj interface{}) error

ShouldBindJSON 是 for c.ShouldBindWith(obj, binding.JSON) 的简写方式。

示例代码:

04

ShouldBindXML

func (*gin.Context).ShouldBindXML(obj interface{}) error

ShouldBindXML 是 c.ShouldBindWith(obj, binding.XML) 的简写方式。

示例代码:

05

ShouldBindQuery

func (*gin.Context).ShouldBindQuery(obj interface{}) error

ShouldBindQuery 是 c.ShouldBindWith(obj, binding.Query) 的简写方式。

ShouldBindQuery 如果 url 查询参数和 post 数据都存在,函数只绑定 url 查询参数而忽略 post 数据。

示例代码:

06

ShouldBindYAML

func (*gin.Context).ShouldBindYAML(obj interface{}) error

ShouldBindYAML 是 c.ShouldBindWith(obj, binding.YAML) 的简写方式。

示例代码:

07

ShouldBindWith

func (*gin.Context).ShouldBindWith(obj interface{}, b binding.Binding) error

ShouldBindWith 使用指定的绑定引擎,绑定传递过来的结构体指针。

示例代码:

08

ShouldBindUri

func (*gin.Context).ShouldBindUri(obj interface{}) error

ShouldBindUri binds the passed struct pointer using the specified binding engine.

示例代码:


推荐阅读:

Gin 学习之安装和快速启动

Gin 学习之响应处理

Gin 学习之 HTTP 请求方法

Gin 学习之接收参数和读取 reader