面包店
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

9 месяцев назад
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package utils
  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. "reflect"
  12. )
  13. var ValidatorTrans ut.Translator
  14. // ValidatorTransInit 验证器错误信息翻译初始化
  15. // local 通常取决于 http 请求头的 'Accept-Language'
  16. func ValidatorTransInit(local string) (err error) {
  17. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  18. zhT := zh.New() //chinese
  19. enT := en.New() //english
  20. uni := ut.New(enT, zhT, enT)
  21. var o bool
  22. ValidatorTrans, o = uni.GetTranslator(local)
  23. if !o {
  24. return fmt.Errorf("uni.GetTranslator(%s) failed", local)
  25. }
  26. // 注册一个方法,从自定义标签label中获取值(用在把字段名映射为中文)
  27. v.RegisterTagNameFunc(func(field reflect.StructField) string {
  28. label := field.Tag.Get("label")
  29. if label == "" {
  30. return field.Name
  31. }
  32. return label
  33. })
  34. // 注册翻译器
  35. switch local {
  36. case "en":
  37. err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans)
  38. case "zh":
  39. err = chTranslations.RegisterDefaultTranslations(v, ValidatorTrans)
  40. default:
  41. err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans)
  42. }
  43. return
  44. }
  45. return
  46. }
  47. // ValidatorTransInitZh 验证器错误信息翻译为中文初始化
  48. func ValidatorTransInitZh() (err error) {
  49. return ValidatorTransInit("zh")
  50. }