[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 err := c.ShouldBind(&info); err != nil { c.JSON(400, gin.H{ "error": err.Error() }) return } c.JSON(200, gin.H{ "data": info.A }) }

在其它脚本语言中,统一获取参数的方法一般都会在框架中做参数类型的顺序/自动检测,兼容性更好。

docs:https://gin-gonic.com/docs/examples/binding-and-validation

Link:https://www.cnblogs.com/farwish/p/12725852.html

原文地址:https://www.cnblogs.com/farwish/p/12725852.html