i18n.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package i18n
  2. import (
  3. "context"
  4. _ "embed"
  5. "encoding/json"
  6. "fmt"
  7. "sync"
  8. "git.dmitriygnatenko.ru/dima/go-common/logger"
  9. "github.com/gofiber/fiber/v2"
  10. )
  11. //go:embed ru.json
  12. var ruJsonContent []byte
  13. type Lang string
  14. const (
  15. CtxLanguageKey = "Language"
  16. Ru Lang = "ru"
  17. Default Lang = Ru
  18. )
  19. var (
  20. once sync.Once
  21. i18n *I18n
  22. )
  23. type I18n struct {
  24. translations map[Lang]map[string]string
  25. }
  26. func Init() error {
  27. var err error
  28. once.Do(func() {
  29. ruTranslations := make(map[string]string)
  30. err = json.Unmarshal(ruJsonContent, &ruTranslations)
  31. if err != nil {
  32. return
  33. }
  34. i18n = &I18n{translations: map[Lang]map[string]string{
  35. Ru: ruTranslations,
  36. }}
  37. })
  38. return err
  39. }
  40. func T(lang Lang, key string, args ...any) string {
  41. if i18n == nil {
  42. logger.Error(context.Background(), "i18n not initialized")
  43. return ""
  44. }
  45. if i18n.translations[lang] == nil {
  46. logger.Warnf(context.Background(), "i18n: language %s not initialized", lang)
  47. return ""
  48. }
  49. if len(args) == 0 {
  50. return i18n.translations[lang][key]
  51. }
  52. return fmt.Sprintf(i18n.translations[lang][key], args...)
  53. }
  54. func Language(c *fiber.Ctx) Lang {
  55. if lang, ok := c.Locals(CtxLanguageKey).(Lang); ok {
  56. return lang
  57. }
  58. return Default
  59. }