Golang中Gin 参数绑定和验证的中间件
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/go-playground/validator/v10"
    "net/http"
)
 
// 定义一个全局验证器,用于复用验证规则
var validate *validator.Validate
 
func init() {
    validate = validator.New()
}
 
// BindAndValidate 是一个中间件,用于参数绑定和验证
func BindAndValidate(c *gin.Context) {
    if err := c.ShouldBind(&model); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        c.Abort()
        return
    }
 
    if err := validate.Struct(model); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        c.Abort()
        return
    }
 
    c.Next()
}
 
type Model struct {
    Field1 string `json:"field1" binding:"required"`
    Field2 int    `json:"field2" binding:"gt=0"`
}
 
var model Model
 
func main() {
    router := gin.Default()
 
    // 使用BindAndValidate作为中间件
    router.POST("/example", BindAndValidate, func(c *gin.Context) {
        fmt.Printf("Model: %#v\n", model)
        c.JSON(http.StatusOK, gin.H{"message": "success"})
    })
 
    // 启动服务器
    router.Run(":8080")
}这个示例代码定义了一个名为BindAndValidate的中间件,用于参数绑定和验证。它使用了validator.v10包来进行验证。在main函数中,我们创建了一个Gin路由器,并为/example路径添加了一个POST请求处理函数,该处理函数使用了我们的BindAndValidate中间件。如果请求中的参数无法绑定或者不符合我们的验证规则,则返回错误信息,否则继续执行后续的处理函数。
评论已关闭