[Gin] 支持 FORM 和 JSON 参数的绑定与验证
Gin 支持对不同传参方式的参数进行统一绑定并验证,比如如下两种格式:
Content-Type: application/x-www-form-urlencoded with a=XX&b=0
Content-Type: application/json with { "a":"XX", "b":0 }
使用方式是,定义参数类结构体,并使用 ShouldBind 统一绑定并验证,代码局部如下:
// @copyright https://cnblogs.com/farwish
type InfoParam struct { A string `form:"a" json:"a" binding:"required"` B int `form:"b" json:"b" binding:"required,gte=0,lte=2"` } func Results(c *gin.Context) { var info InfoParam
// If `GET`, only `Form` binding engine (`query`) used.
// If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
// See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
if err := c.ShouldBind(&info); err != nil { c.JSON(400, gin.H{ "error": err.Error() }) return } c.JSON(200, gin.H{ "data": info.A }) }
在其它脚本语言中,统一获取参数的方法一般都会在框架中做参数类型的顺序/自动检测,兼容性更好。
GinDoc:https://github.com/gin-gonic/gin/#model-binding-and-validation
ValidatorDoc:https://godoc.org/github.com/go-playground/validator