tijl.dev-core/modules/i18n/i18n.go
tijl b8d7a8c4cf
All checks were successful
build / build (push) Successful in 36s
release-tag / release-image (push) Successful in 16m28s
basic app implementation
2024-08-25 17:43:55 +02:00

99 lines
2.0 KiB
Go

package i18n
import (
"embed"
"encoding/json"
"path/filepath"
"strings"
log "git.tijl.dev/tijl/tijl.dev-core/modules/logger"
"github.com/gofiber/fiber/v2"
)
var translations map[string]map[string]string
const DefaultLang = "en"
func RegisterTranslations(embed embed.FS, location string) {
amountFilesLoaded := 0
if translations == nil {
translations = make(map[string]map[string]string)
}
files, err := embed.ReadDir(location)
if err != nil {
log.Fatal().Err(err)
}
for _, file := range files {
if file.IsDir() {
continue
}
if filepath.Ext(file.Name()) != ".json" {
continue
}
lang := strings.TrimSuffix(file.Name(), filepath.Ext(file.Name()))
data, err := embed.ReadFile(filepath.Join(location, file.Name()))
if err != nil {
log.Error().Err(err).Msg("Failed to read file")
continue
}
var messages map[string]string
if err := json.Unmarshal(data, &messages); err != nil {
log.Error().Err(err).Msg("Failed to decode JSON")
continue
}
if translations[lang] == nil {
translations[lang] = make(map[string]string)
}
for key, value := range messages {
translations[lang][key] = value
}
amountFilesLoaded++
//log.Debug().Str("filename", file.Name()).Msg("i18n.RegisterTranslations: loaded")
}
log.Debug().Int("amountFilesLoaded", amountFilesLoaded).Msg("i18n.RegisterTranslations:")
}
func Translate(c *fiber.Ctx, key string) string {
lang := c.Cookies("language")
if messages, ok := translations[lang]; ok {
if message, ok := messages[key]; ok {
return message
}
}
if messages, ok := translations[DefaultLang]; ok {
if message, ok := messages[key]; ok {
return message
}
}
return key
}
func GetLanguage(c *fiber.Ctx) string {
lang := c.Cookies("language")
if _, ok := translations[lang]; ok {
return lang
} else {
return DefaultLang
}
}
func GetTranslations(lang string) map[string]string {
if messages, ok := translations[lang]; ok {
return messages
}
return translations[DefaultLang]
}