May 8, 2024
第三方包
#
github.com/go-playground/validator/v10
常用参数
#
required //必填;
len=11 //长度=11;
min=3 //如果是数字,验证的是数据大小范围,最小值为3,如果是文本,验证的是最小长度为3,
max=6 //如果是数字,验证的是数字最大值为6,如果是文本,验证的是最大长度为6
mail //验证邮箱
gt=3 //对于文本就是长度>=3
lt=6 //对于文本就是长度<=6
翻译中间件
#
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/en"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
validator "github.com/go-playground/validator/v10"
enTranslations "github.com/go-playground/validator/v10/translations/en"
zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)
func Translations() gin.HandlerFunc {
return func(c *gin.Context) {
//locale := .GetHeader("Acept-Language")
locale := "zh"
uni := ut.New(en.New(), zh.New())
trans, _ := uni.GetTranslator(locale)
v, ok := binding.Validator.Engine().(*validator.Validate)
if ok {
switch locale {
case "zh":
_ = zhTranslations.RegisterDefaultTranslations(v, trans)
case "en":
_ = enTranslations.RegisterDefaultTranslations(v, trans)
default:
_ = zhTranslations.RegisterDefaultTranslations(v, trans)
}
c.Set("trans", trans)
}
c.Next()
}
}
参数校验及错误翻译
#
/* type Register struct {
UserName string `form:"user_name" json:"user_name" binding:"required,min=1"`
Pass string `form:"pass" json:"pass" binding:"required,min=6,max=20"`
Captcha string `form:"captcha" json:"captcha" binding:"required,len=4"`
Age float64 `form:"age" json:"age" binding:"required,min=1,max=200"`
// 注意: 如果你的表单参数含有0值是允许提交的,必须用指针类型(*float64),而 float64 类型则认为 0 值不合格
Status *float64 `form:"status" json:"status" binding:"required,min=0,max=1"`
} */
package utils
import (
"fmt"
"github.com/gin-gonic/gin"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
)
// ShouldBindJSON 封装绑定及错误翻译
func ShouldBindJSON(c *gin.Context, obj interface{}) error {
if err := c.ShouldBindJSON(obj); err != nil {
//翻译错误信息
if errs, ok := err.(validator.ValidationErrors); ok {
v := c.Value("trans")
trans, _ := v.(ut.Translator)
var e string
for _, v := range errs.Translate(trans) {
e += fmt.Sprintf("%s ", v)
}
return fmt.Errorf(e)
}
}
return nil
}