package i18n import ( "context" _ "embed" "encoding/json" "fmt" "sync" "git.dmitriygnatenko.ru/dima/go-common/logger" "github.com/gofiber/fiber/v2" ) //go:embed ru.json var ruJsonContent []byte type Lang string const ( CtxLanguageKey = "Language" Ru Lang = "ru" Default Lang = Ru ) var ( once sync.Once i18n *I18n ) type I18n struct { translations map[Lang]map[string]string } func Init() error { var err error once.Do(func() { ruTranslations := make(map[string]string) err = json.Unmarshal(ruJsonContent, &ruTranslations) if err != nil { return } i18n = &I18n{translations: map[Lang]map[string]string{ Ru: ruTranslations, }} }) return err } func T(lang Lang, 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 "" } if len(args) == 0 { return i18n.translations[lang][key] } return fmt.Sprintf(i18n.translations[lang][key], args...) } func Language(c *fiber.Ctx) Lang { if lang, ok := c.Locals(CtxLanguageKey).(Lang); ok { return lang } return Default }