[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