package base import ( "github.com/gin-gonic/gin/binding" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" zh_translations "github.com/go-playground/validator/v10/translations/zh" "log" "reflect" "strings" ) var translator ut.Translator type ErrMsg = map[string]string // 自定义验证器的错误消息映射表 var customMsg = map[string]string{ //"exists": "{0}对应的记录不存在", } // initValidateMsg 初始验证器消息处理器(中间件) func initValidateMsg() { uni := ut.New(zh.New()) translator, _ = uni.GetTranslator("zh") v := binding.Validator.Engine().(*validator.Validate) _ = zh_translations.RegisterDefaultTranslations(v, translator) // 注册自定验证器的翻译 tf := func(ut ut.Translator, fe validator.FieldError) string { msg, err := ut.T(fe.Tag(), fe.Field()) if err != nil { log.Println(err) } return msg } for tag, text := range customMsg { _ = v.RegisterTranslation(tag, translator, func(trans ut.Translator) error { _ = trans.Add(tag, text, false) return nil }, tf) } v.RegisterTagNameFunc(func(fld reflect.StructField) string { name := "" tagJson := fld.Tag.Get("json") if len(tagJson) > 0 { tmpName := strings.SplitN(tagJson, ",", 2)[0] if tmpName != "-" { name = tmpName } } return name }) } // Translate 翻译错误消息的方法 func Translate(err error) map[string]string { errs, ok := err.(validator.ValidationErrors) if !ok { return nil } errMsg := make(ErrMsg, len(errs)) for _, e := range errs { errMsg[e.Field()] = e.Translate(translator) } return errMsg } func init() { // initValidateMsg() }