trans.go 1.26 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
package validate

import (
	"errors"
	"github.com/go-playground/locales/en"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	//zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
)

var (
	vt    *validator.Validate
	trans ut.Translator
)

// 初始化验证器和翻译
func init() {
	registerDefault()
}

func registerDefault() {
	vt = validator.New()
	trans = registerTranslate(vt)
}

func registerTranslate(v *validator.Validate) ut.Translator {
	//zhT := zh.New()
	enT := en.New()

	uni := ut.New(enT, enT)
	tr, _ := uni.GetTranslator("en")
	_ = enTranslations.RegisterDefaultTranslations(v, tr)
	return tr
}

// Struct 验证结构体
func Struct(data interface{}) error {
	return TransErr(vt.Struct(data))
}

// Trans 翻译错误信息
func Trans(err error) (msg string) {
	if err == nil {
		return
	}

	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
}

func TransErr(err error) error {
	if err == nil {
		return nil
	}
	return errors.New(Trans(err))
}