tijl.dev-core/internal/i18n/i18n.go

72 lines
1.6 KiB
Go
Raw Normal View History

2024-08-19 22:32:43 +02:00
package i18n
import (
"encoding/json"
"github.com/gofiber/fiber/v2"
"log"
"os"
"path/filepath"
)
var translations map[string]map[string]string
const DefaultLang = "en"
// LoadTranslations loads translations from JSON files
func LoadTranslations() {
translations = make(map[string]map[string]string)
dir := "locales"
files, err := filepath.Glob(filepath.Join(dir, "*.json"))
if err != nil {
log.Fatalf("Error loading language files: %v", err)
}
for _, file := range files {
lang := filepath.Base(file)
lang = lang[:len(lang)-len(filepath.Ext(lang))]
file, err := os.Open(file)
if err != nil {
log.Printf("Error opening translation file %s: %v", file, err)
continue
}
defer file.Close()
var messages map[string]string
if err := json.NewDecoder(file).Decode(&messages); err != nil {
log.Printf("Error decoding translation file %s: %v", file, err)
continue
}
translations[lang] = messages
}
}
// Translate returns the translated message for the given key and context
func Translate(c *fiber.Ctx, key string) string {
lang := c.Locals("lang").(string)
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
}
// TranslateFunc returns a function for use in templates
func TranslateFunc() func(*fiber.Ctx, string) string {
return func(c *fiber.Ctx, key string) string {
return Translate(c, key)
}
}
// GetTranslations returns the translations map
func GetTranslations() map[string]map[string]string {
return translations
}