1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package unity
- import (
- "fmt"
- "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"
- "github.com/go-playground/validator/v10"
- enTranslations "github.com/go-playground/validator/v10/translations/en"
- zhTranslations "github.com/go-playground/validator/v10/translations/zh"
- )
- var Validate *validator.Validate // 声明一个全局的validator.Validate实例
- var Trans ut.Translator // 声明一个全局的Translator变量
- // InitializeValidator 初始化全局验证器并注册翻译器
- func InitializeValidator(local string) error {
- Validate = validator.New()
- // 初始化英语和中文翻译器
- zhT := zh.New()
- enT := en.New()
- // 创建一个通用翻译器实例,传入多个翻译器
- uni := ut.New(enT, zhT, enT)
- // 尝试从通用翻译器中获取指定语言的翻译器
- var found bool
- Trans, found = uni.GetTranslator(local)
- if !found {
- return fmt.Errorf("failed to find translator for %s", local)
- }
- // 注册翻译到验证器
- switch local {
- case "en":
- err := enTranslations.RegisterDefaultTranslations(Validate, Trans)
- if err != nil {
- return err
- }
- case "zh":
- err := zhTranslations.RegisterDefaultTranslations(Validate, Trans)
- if err != nil {
- return err
- }
- default:
- err := enTranslations.RegisterDefaultTranslations(Validate, Trans)
- if err != nil {
- return err
- }
- }
- // 如果您使用 Gin,并想替换 Gin 的默认验证器引擎,请执行以下操作
- if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
- *v = *Validate
- } else {
- return fmt.Errorf("failed to replace Gin's default validator engine")
- }
- return nil
- }
|