universal-translator.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package ut
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/go-playground/locales/locales-list"
  6. )
  7. // UniversalTranslator holds all locale & translation data
  8. type UniversalTranslator struct {
  9. translators map[string]Translator
  10. fallback Translator
  11. }
  12. // New returns a new UniversalTranslator instance set with
  13. // the fallback locale and locales it should support
  14. func New(fallback string, supportedLocales ...string) (*UniversalTranslator, error) {
  15. t := &UniversalTranslator{
  16. translators: make(map[string]Translator),
  17. }
  18. lcMapping := make(localeslist.LocaleMap)
  19. for loc, tf := range localeslist.Map() {
  20. lcMapping[strings.ToLower(loc)] = tf
  21. }
  22. var ok bool
  23. var lc string
  24. var tf localeslist.LocaleFunc
  25. fallbackLower := strings.ToLower(fallback)
  26. for _, loc := range supportedLocales {
  27. lc = strings.ToLower(loc)
  28. tf, ok = lcMapping[lc]
  29. if !ok {
  30. return nil, &ErrLocaleNotFound{text: fmt.Sprintf("locale '%s' could not be found, perhaps it is not supported.", loc)}
  31. }
  32. if fallbackLower == lc {
  33. t.fallback = newTranslator(tf())
  34. t.translators[lc] = t.fallback
  35. continue
  36. }
  37. t.translators[lc] = newTranslator(tf())
  38. }
  39. if t.fallback == nil {
  40. return nil, &ErrLocaleNotFound{text: fmt.Sprintf("fallback locale '%s' could not be found", fallback)}
  41. }
  42. return t, nil
  43. }
  44. // FindTranslator trys to find a Translator based on an array of locales
  45. // and returns the first one it can find, otherwise returns the
  46. // fallback translator.
  47. func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator) {
  48. var ok bool
  49. for _, locale := range locales {
  50. if trans, ok = t.translators[strings.ToLower(locale)]; ok {
  51. return
  52. }
  53. }
  54. return t.fallback
  55. }
  56. // GetTranslator returns the specified translator for the given locale,
  57. // or fallback if not found
  58. func (t *UniversalTranslator) GetTranslator(locale string) Translator {
  59. if t, ok := t.translators[strings.ToLower(locale)]; ok {
  60. return t
  61. }
  62. return t.fallback
  63. }