代码之家  ›  专栏  ›  技术社区  ›  devmarkpro

GIN框架中的自定义验证

go
  •  0
  • devmarkpro  · 技术社区  · 6 年前

    我有一份和歌朗一起写的申请书 gin framework . 我想编写一个中间件来定制所有错误消息,特别是在 BindJSON .

    这是中间件:

    func Errors() gin.HandlerFunc {
        return func(c *gin.Context) {
            c.Next()
            // Only run if there are some errors to handle
            if len(c.Errors) > 0 {
                for _, e := range c.Errors {
                    // Find out what type of error it is
                    switch e.Type {
                    case gin.ErrorTypePublic:
                        // Only output public errors if nothing has been written yet
                        if !c.Writer.Written() {
                            c.JSON(c.Writer.Status(), gin.H{"Error": e.Error()})
                        }
                    case gin.ErrorTypeBind:
                        errs := e.Err.(validator.ValidationErrors)
                        list := make(map[int]string)
    
                        fmt.Println(errs)
                        for field, err := range errs {
                            list[field] = validationErrorToText(err)
                        }
                        // Make sure we maintain the preset response status
                        status := http.StatusBadRequest
                        if c.Writer.Status() != http.StatusOK {
                            status = c.Writer.Status()
                        }
                        c.JSON(status, gin.H{"Errors": list})
    
                    default:
                        c.JSON(http.StatusBadRequest, gin.H{"Errors": c.Errors.JSON()})
                    }
    
                }
                // If there was no public or bind error, display default 500 message
                if !c.Writer.Written() {
                    c.JSON(http.StatusInternalServerError, gin.H{"Error": errorInternalError.Error()})
                }
            }
        }
    }
    

    功能非常简单,它可以 gin 错误并根据错误类型执行某些操作!问题在于 gin.ErrorTypeBind 当我尝试将错误映射到验证错误时: e.Err.(validator.ValidationErrors) . 我有这个错误

    interface conversion: error is validator.ValidationErrors, not validator.ValidationErrors (types from different packages)

    以下是导入包的列表:

    import (
        "errors"
        "fmt"
        "net/http"
    
        "github.com/gin-gonic/gin"
        "gopkg.in/go-playground/validator.v9"
    )
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   dave    6 年前

    看着 source code of gin 我看到了:

    import (
        "gopkg.in/go-playground/validator.v8"
    )
    

    但是你在使用 "gopkg.in/go-playground/validator.v9"

    推荐文章