You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1003B

  1. package translation
  2. import (
  3. "context"
  4. "golang.org/x/text/language"
  5. )
  6. // Default values.
  7. const (
  8. DefaultDomain = "messages"
  9. )
  10. // Provider for translate key.
  11. type Provider interface {
  12. Translate(ctx context.Context, key string, opt Translate) string
  13. }
  14. // TranslatorOption options translator.
  15. type TranslatorOption func(*Translator)
  16. // New creates new translator.
  17. func New(locale language.Tag, provider Provider, opts ...TranslatorOption) *Translator {
  18. tr := Translator{
  19. locale: locale,
  20. provider: provider,
  21. domain: DefaultDomain,
  22. }
  23. for _, o := range opts {
  24. o(&tr)
  25. }
  26. return &tr
  27. }
  28. // Translator struct.
  29. type Translator struct {
  30. provider Provider
  31. domain string
  32. locale language.Tag
  33. }
  34. // Trans translates key by options.
  35. func (t *Translator) Trans(ctx context.Context, key string, opts ...Option) string {
  36. opt := Translate{
  37. Locale: FromContext(ctx, t.locale),
  38. Domain: t.domain,
  39. }
  40. for _, o := range opts {
  41. o(&opt)
  42. }
  43. return t.provider.Translate(ctx, key, opt)
  44. }