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