[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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM