package main import ( "encoding/json" "log" "path/filepath" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) var bundle *i18n.Bundle func init() { if err := initI18nBundle(); err != nil { // Fail fast during startup in tests/builds log.Fatalf("failed to initialize i18n bundle: %v", err) } } func initI18nBundle() error { // Initialize the i18n bundle with English as default bundle = i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("json", json.Unmarshal) // Load translation files from app/ directory files := []string{ filepath.Join("app", "active.en.json"), filepath.Join("app", "active.id.json"), filepath.Join("app", "active.zh.json"), } for _, f := range files { if _, err := bundle.LoadMessageFile(f); err != nil { return err } } return nil } // Translate returns the translated string for a given locale and message ID. func Translate(locale, messageID string) string { loc := i18n.NewLocalizer(bundle, locale) s, err := loc.Localize(&i18n.LocalizeConfig{MessageID: messageID}) if err != nil || s == "" { // Fallback to the messageID if translation is missing return messageID } return s }