translate.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package api
  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. chTranslations "github.com/go-playground/validator/v10/translations/zh"
  11. )
  12. // transInit local 通常取决于 http 请求头的 'Accept-Language'
  13. func transInit(local string) (trans ut.Translator, err error) {
  14. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  15. zhT := zh.New() //chinese
  16. enT := en.New() //english
  17. uni := ut.New(enT, zhT, enT)
  18. var o bool
  19. //register translate
  20. // 注册翻译器
  21. switch local {
  22. case "zh", "zh-CN":
  23. trans, o = uni.GetTranslator("zh")
  24. if !o {
  25. return nil, fmt.Errorf("uni.GetTranslator(%s) failed", "zh")
  26. }
  27. err = chTranslations.RegisterDefaultTranslations(v, trans)
  28. default:
  29. trans, o = uni.GetTranslator("en")
  30. if !o {
  31. return nil, fmt.Errorf("uni.GetTranslator(%s) failed", "en")
  32. }
  33. err = enTranslations.RegisterDefaultTranslations(v, trans)
  34. }
  35. return
  36. }
  37. return
  38. }