go - Gin 框架中的自定义验证
问题描述
我有一个用 golang 编写的应用程序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"
)
解决方案
查看杜松子酒的源代码,我看到了这个:
import (
"gopkg.in/go-playground/validator.v8"
)
但你正在使用"gopkg.in/go-playground/validator.v9"
推荐阅读
- javascript - Angularjs-在角度变量中使用 url 作为嵌入式 youtube src
- angularjs - 在 HTML 中显示 angularJS 范围元素
- apache-spark - Pyspark 按位置推断时区
- html - 新闻模板,如菜单布局
- pandas - csv 文件中的字符串和引号
- javascript - 什么是 Google Optimize 中 Javascript 变量定位中的全局变量名称?
- php - 如何在 ubuntu 终端本地检查 php 脚本设置?
- r - 在调用 RcmdrPlugin.BCA 时,我收到此错误消息:找不到对象“importRODBCtable”
- javascript - 是什么阻止了这个网页缩小到小于 530 像素的宽度?
- elasticsearch - 使用 Zipkin+ElasticSearch+Sleuth+rabbitMQ 找不到“服务”