trans.go 945 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package helpers
  2. import (
  3. "reflect"
  4. "github.com/go-playground/locales/ru"
  5. ut "github.com/go-playground/universal-translator"
  6. "github.com/go-playground/validator/v10"
  7. ruTranslations "github.com/go-playground/validator/v10/translations/ru"
  8. )
  9. var fieldNames = map[string]string{
  10. "Tag": "Тег",
  11. "Title": "Название",
  12. "Image": "Картинка",
  13. "PublishTime": "Дата публикации",
  14. "Text": "Текст",
  15. }
  16. func GetDefaultTranslator(v *validator.Validate) (ut.Translator, error) {
  17. var err error
  18. localeRu := ru.New()
  19. uniTrans := ut.New(localeRu, localeRu)
  20. trans, _ := uniTrans.GetTranslator(localeRu.Locale())
  21. if err = ruTranslations.RegisterDefaultTranslations(v, trans); err != nil {
  22. return nil, err
  23. }
  24. v.RegisterTagNameFunc(func(field reflect.StructField) string {
  25. if name, ok := fieldNames[field.Name]; ok {
  26. return name
  27. }
  28. return field.Name
  29. })
  30. return trans, nil
  31. }