translation/translation.go
2025-06-23 21:36:40 +02:00

60 lines
1.4 KiB
Go

package translation
import (
"embed"
"encoding/json"
"fmt"
"strings"
)
var defaultCulture = "en"
var sources = make(map[string]map[string]string)
var translationFiles embed.FS
func SetDefaultCulture(culture string) {
defaultCulture = strings.ToLower(culture)
}
func Init(files embed.FS) {
translationFiles = files
}
func Get(key string, culture string, args ...string) string {
source, err := 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 loadSource(culture string) (map[string]string, error) {
source, ok := sources[culture]
if ok {
return source, nil
}
data, err := translationFiles.ReadFile(fmt.Sprintf("%s.json", strings.ToLower(culture)))
if err != nil {
data, err = translationFiles.ReadFile(fmt.Sprintf("%s.json", defaultCulture))
if err != nil {
return source, fmt.Errorf("can not load translation source for culture %s DefaultCulture: %s", culture, defaultCulture)
}
}
err = json.Unmarshal(data, &source)
if err != nil {
return source, fmt.Errorf("can not parse translation source %s", culture)
}
sources[culture] = source
return sources[culture], nil
}