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 }