trans.go 1.11 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11
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 (
kzkzzzz's avatar
kzkzzzz committed
12 13
	vt    *validator.Validate
	trans ut.Translator
kzkzzzz's avatar
kzkzzzz committed
14 15
)

16 17 18 19 20 21
// 初始化验证器和翻译
func init() {
	vt = validator.New()
	trans = newTranslate(vt)
}

kzkzzzz's avatar
kzkzzzz committed
22 23 24 25 26
func newTranslate(v *validator.Validate) ut.Translator {
	zhT := zh.New()
	enT := en.New()

	uni := ut.New(enT, zhT)
kzkzzzz's avatar
kzkzzzz committed
27 28 29
	tr, _ := uni.GetTranslator("zh")
	_ = zhTranslations.RegisterDefaultTranslations(v, tr)
	return tr
kzkzzzz's avatar
kzkzzzz committed
30 31
}

32
// GrtTrans 获取翻译实例
kzkzzzz's avatar
kzkzzzz committed
33
func GrtTrans() ut.Translator {
kzkzzzz's avatar
kzkzzzz committed
34
	return trans
kzkzzzz's avatar
kzkzzzz committed
35 36
}

37
// Struct 验证结构体
kzkzzzz's avatar
kzkzzzz committed
38 39 40
func Struct(data interface{}) error {
	return vt.Struct(data)
}
kzkzzzz's avatar
kzkzzzz committed
41

42
// TransError 翻译错误信息
kzkzzzz's avatar
kzkzzzz committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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
}