123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package i18n
- import (
- "context"
- _ "embed"
- "encoding/json"
- "fmt"
- "sync"
- "git.dmitriygnatenko.ru/dima/go-common/logger"
- )
- //go:embed ru.json
- var ruJsonContent []byte
- //go:embed en.json
- var enJsonContent []byte
- type Language string
- const (
- Ru Language = "ru"
- En Language = "en"
- Default Language = Ru
- LangParam = "lang"
- )
- var (
- once sync.Once
- i18n *I18n
- )
- type I18n struct {
- translations map[Language]map[string]string
- }
- func Init() error {
- var err error
- once.Do(func() {
- ruTranslations := make(map[string]string)
- enTranslations := make(map[string]string)
- err = json.Unmarshal(ruJsonContent, &ruTranslations)
- if err != nil {
- return
- }
- err = json.Unmarshal(enJsonContent, &enTranslations)
- if err != nil {
- return
- }
- i18n = &I18n{translations: map[Language]map[string]string{
- Ru: ruTranslations,
- En: enTranslations,
- }}
- })
- return err
- }
- func T(lang Language, key string, args ...any) string {
- if i18n == nil {
- logger.Error(context.Background(), "i18n not initialized")
- return ""
- }
- if i18n.translations[lang] == nil {
- logger.Warnf(context.Background(), "i18n: language %s not initialized", lang)
- return ""
- }
- var translated string
- if len(args) == 0 {
- translated = i18n.translations[lang][key]
- } else {
- translated = fmt.Sprintf(i18n.translations[lang][key], args...)
- }
- if len(translated) == 0 {
- logger.Warnf(
- context.Background(),
- "i18n: language %s translation %s is not found", lang, key,
- )
- }
- return translated
- }
|