2024-10-21 16:46:25 +03:00
|
|
|
package lang
|
2024-05-03 15:40:40 +03:00
|
|
|
|
|
|
|
import (
|
2024-05-18 16:15:20 +03:00
|
|
|
"embed"
|
2024-05-03 15:40:40 +03:00
|
|
|
"encoding/json"
|
|
|
|
"log/slog"
|
|
|
|
)
|
|
|
|
|
2024-10-21 16:46:25 +03:00
|
|
|
//go:embed lang
|
|
|
|
var lang embed.FS
|
|
|
|
var translations = map[string]string{}
|
2024-05-03 15:40:40 +03:00
|
|
|
|
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 {
|
2024-10-21 16:46:25 +03:00
|
|
|
filename := "lang/" + language + ".json"
|
|
|
|
fileContents, err := lang.ReadFile(filename)
|
2024-05-18 16:15:20 +03:00
|
|
|
if err != nil {
|
|
|
|
slog.Error("error reading language file",
|
|
|
|
"error", err,
|
|
|
|
"file", filename)
|
|
|
|
return err
|
|
|
|
}
|
2024-10-21 16:46:25 +03:00
|
|
|
return json.Unmarshal(fileContents, &translations)
|
2024-05-03 15:40:40 +03:00
|
|
|
}
|
2024-10-21 16:46:25 +03:00
|
|
|
translations = map[string]string{} // Clear the map to avoid previous language remaining
|
2024-06-17 00:54:55 +03:00
|
|
|
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-10-21 16:46:25 +03:00
|
|
|
// Translate attempts to match an id to a string in current language.
|
|
|
|
func Translate(id string) string {
|
|
|
|
if v, ok := translations[id]; !ok {
|
2024-05-03 15:40:40 +03:00
|
|
|
return id
|
|
|
|
} else {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
}
|