zh_cn.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package unity
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin/binding"
  5. "github.com/go-playground/locales/en"
  6. "github.com/go-playground/locales/zh"
  7. ut "github.com/go-playground/universal-translator"
  8. "github.com/go-playground/validator/v10"
  9. enTranslations "github.com/go-playground/validator/v10/translations/en"
  10. zhTranslations "github.com/go-playground/validator/v10/translations/zh"
  11. )
  12. var Validate *validator.Validate // 声明一个全局的validator.Validate实例
  13. var Trans ut.Translator // 声明一个全局的Translator变量
  14. // InitializeValidator 初始化全局验证器并注册翻译器
  15. func InitializeValidator(local string) error {
  16. Validate = validator.New()
  17. // 初始化英语和中文翻译器
  18. zhT := zh.New()
  19. enT := en.New()
  20. // 创建一个通用翻译器实例,传入多个翻译器
  21. uni := ut.New(enT, zhT, enT)
  22. // 尝试从通用翻译器中获取指定语言的翻译器
  23. var found bool
  24. Trans, found = uni.GetTranslator(local)
  25. if !found {
  26. return fmt.Errorf("failed to find translator for %s", local)
  27. }
  28. // 注册翻译到验证器
  29. switch local {
  30. case "en":
  31. err := enTranslations.RegisterDefaultTranslations(Validate, Trans)
  32. if err != nil {
  33. return err
  34. }
  35. case "zh":
  36. err := zhTranslations.RegisterDefaultTranslations(Validate, Trans)
  37. if err != nil {
  38. return err
  39. }
  40. default:
  41. err := enTranslations.RegisterDefaultTranslations(Validate, Trans)
  42. if err != nil {
  43. return err
  44. }
  45. }
  46. // 如果您使用 Gin,并想替换 Gin 的默认验证器引擎,请执行以下操作
  47. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  48. *v = *Validate
  49. } else {
  50. return fmt.Errorf("failed to replace Gin's default validator engine")
  51. }
  52. return nil
  53. }