package translation import ( "embed" "encoding/json" "fmt" "strings" "git.apihub24.de/admin/generic-di" ) func init() { di.Injectable(newTranslationService) } type ITranslationService interface { Init(files embed.FS) SetDefaultCulture(culture string) Get(key string, culture string, args ...string) string } type translationService struct { defaultCulture string translationFiles embed.FS sources map[string]map[string]string } func newTranslationService() ITranslationService { return &translationService{ defaultCulture: "en", translationFiles: embed.FS{}, sources: make(map[string]map[string]string), } } func (translation *translationService) Init(files embed.FS) { translation.translationFiles = files } func (translation *translationService) SetDefaultCulture(culture string) { translation.defaultCulture = strings.ToLower(culture) } func (translation *translationService) Get(key string, culture string, args ...string) string { source, err := translation.loadSource(culture) if err != nil { return fmt.Sprintf("unknown error: %s", err.Error()) } value, ok := source[key] if !ok { return fmt.Sprintf("no value for key %s found in source %s", key, culture) } if len(args) > 0 { var tmpArgs = make([]any, len(args)) for idx, arg := range args { tmpArgs[idx] = arg } return fmt.Sprintf(value, tmpArgs...) } return value } func (translation *translationService) loadSource(culture string) (map[string]string, error) { source, ok := translation.sources[culture] if ok { return source, nil } data, err := translation.translationFiles.ReadFile(fmt.Sprintf("%s.json", strings.ToLower(culture))) if err != nil { data, err = translation.translationFiles.ReadFile(fmt.Sprintf("%s.json", translation.defaultCulture)) if err != nil { return source, fmt.Errorf("can not load translation source for culture %s DefaultCulture: %s", culture, translation.defaultCulture) } } err = json.Unmarshal(data, &source) if err != nil { return source, fmt.Errorf("can not parse translation source %s", culture) } translation.sources[culture] = source return translation.sources[culture], nil }