Go Gin框架中的自定义验证
我有一个用golangGo Gin框架中的自定义验证,go,Go,我有一个用golanggin框架编写的应用程序。我想编写一个中间件来定制所有错误消息,特别是在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 {
gin框架编写的应用程序
。我想编写一个中间件来定制所有错误消息,特别是在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)
。
我犯了这个错误
接口转换:错误是validator.ValidationErrors,而不是validator.ValidationErrors(来自不同包的类型)
以下是导入包的列表:
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"gopkg.in/go-playground/validator.v9"
)
看看这张照片,我看到了:
import (
"gopkg.in/go-playground/validator.v8"
)
但是您使用的是“gopkg.in/go playder/validator.v9”