package validate import ( "github.com/go-playground/locales/en" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" zhTranslations "github.com/go-playground/validator/v10/translations/zh" ) var ( vt *validator.Validate trans ut.Translator ) func newTranslate(v *validator.Validate) ut.Translator { zhT := zh.New() enT := en.New() uni := ut.New(enT, zhT) tr, _ := uni.GetTranslator("zh") _ = zhTranslations.RegisterDefaultTranslations(v, tr) return tr } func init() { vt = validator.New() trans = newTranslate(vt) } func GrtTrans() ut.Translator { return trans } func Struct(data interface{}) error { return vt.Struct(data) } func TransError(err error) (msg string) { switch v := err.(type) { case validator.ValidationErrors: if len(v) > 0 { msg = v[0].Translate(trans) } else { msg = v.Error() } case validator.FieldError: msg = v.Translate(trans) default: msg = err.Error() } return }