From f4a1350a41f75e151d90d84ae9331a0e3063ff41 Mon Sep 17 00:00:00 2001 From: Harvey Kandola Date: Wed, 16 Mar 2022 13:32:48 -0400 Subject: [PATCH] i18n server-side loading and setup --- core/i18n/localize.go | 74 +++++++++++++++++++++++++++++++++++++++++++ edition/community.go | 7 ++++ 2 files changed, 81 insertions(+) create mode 100644 core/i18n/localize.go diff --git a/core/i18n/localize.go b/core/i18n/localize.go new file mode 100644 index 00000000..27ccaa69 --- /dev/null +++ b/core/i18n/localize.go @@ -0,0 +1,74 @@ +package i18n + +import ( + "embed" + "encoding/json" + "fmt" + + "github.com/documize/community/core/asset" + + "github.com/pkg/errors" +) + +var localeMap map[string]map[string]string + +// type translation struct { +// Key string `json:"key"` +// Value string `json:"value"` +// } + +// SupportedLocales returns array of locales. +func SupportedLocales() (locales []string) { + locales = append(locales, "en-US") + + return +} + +// Intialize will load language files +func Initialize(e embed.FS) (err error) { + localeMap = make(map[string]map[string]string) + + locales := SupportedLocales() + + for i := range locales { + content, _, err := asset.FetchStatic(e, "i18n/"+locales[i]+".json") + if err != nil { + err = errors.Wrap(err, fmt.Sprintf("missing locale %s", locales[i])) + return err + } + + var payload interface{} + json.Unmarshal([]byte(content), &payload) + m := payload.(map[string]interface{}) + + // translations := []translation{} + + translations := make(map[string]string) + + for j := range m { + translations[j] = m[j].(string) + } + + localeMap[locales[i]] = translations + } + + return nil +} + +// Localize will returns string value for given key using specified locale). +// e.g. locale = "en-US", key = "admin_billing" +func Localize(locale, key string) (s string) { + l, ok := localeMap[locale] + if !ok { + // fallback + l = localeMap["en-US"] + } + + s, ok = l[key] + if !ok { + // missing translation key is echo'ed back + s = fmt.Sprintf("!! %s !!", key) + } + + return +} diff --git a/edition/community.go b/edition/community.go index 27f44cf0..c6ebba7d 100644 --- a/edition/community.go +++ b/edition/community.go @@ -18,6 +18,7 @@ import ( "os" "github.com/documize/community/core/env" + "github.com/documize/community/core/i18n" "github.com/documize/community/domain" "github.com/documize/community/domain/section" "github.com/documize/community/domain/store" @@ -62,6 +63,12 @@ func main() { } rt.Log.Info("Configuration: " + rt.Flags.ConfigSource) + // i18n + err := i18n.Initialize(rt.Assets) + if err != nil { + rt.Log.Error("i18n", err) + } + // Start database init. boot.InitRuntime(&rt, &s)