2024-05-03 15:40:40 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2024-05-18 16:15:20 +03:00
|
|
|
"embed"
|
2024-05-03 15:40:40 +03:00
|
|
|
"encoding/json"
|
|
|
|
"log/slog"
|
|
|
|
)
|
|
|
|
|
2024-05-18 16:15:20 +03:00
|
|
|
//go:embed i18n
|
|
|
|
var I18n embed.FS
|
2024-05-03 15:40:40 +03:00
|
|
|
var Translations = map[string]string{}
|
|
|
|
|
2024-06-17 00:54:55 +03:00
|
|
|
// SetLanguage loads a json file for selected language into the Translations map, with English language as a fallback.
|
2024-05-18 16:15:20 +03:00
|
|
|
func SetLanguage(language string) error {
|
|
|
|
loadLanguage := func(language string) error {
|
|
|
|
filename := "i18n/" + language + ".json"
|
|
|
|
fileContents, err := I18n.ReadFile(filename)
|
|
|
|
if err != nil {
|
|
|
|
slog.Error("error reading language file",
|
|
|
|
"error", err,
|
|
|
|
"file", filename)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return json.Unmarshal(fileContents, &Translations)
|
2024-05-03 15:40:40 +03:00
|
|
|
}
|
2024-06-17 00:54:55 +03:00
|
|
|
Translations = map[string]string{} // Clear the map to avoid previous language remaining
|
|
|
|
err := loadLanguage("en") // Load English as fallback
|
2024-05-03 15:40:40 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-05-18 16:15:20 +03:00
|
|
|
return loadLanguage(language)
|
2024-05-03 15:40:40 +03:00
|
|
|
}
|
|
|
|
|
2024-06-17 00:54:55 +03:00
|
|
|
// TranslatableText attempts to match an id to a string in current language.
|
2024-05-03 15:40:40 +03:00
|
|
|
func TranslatableText(id string) string {
|
|
|
|
if v, ok := Translations[id]; !ok {
|
|
|
|
return id
|
|
|
|
} else {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
}
|