-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalization.go
More file actions
90 lines (76 loc) · 2.09 KB
/
localization.go
File metadata and controls
90 lines (76 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package engine
import (
"log"
"os"
"strings"
"sync"
)
type LocalizationManager struct {
currentLang string
catalog Catalog
mutex sync.RWMutex
}
var (
globalLocManager *LocalizationManager
once sync.Once
)
// GetLocalizationManager returns singleton instance of LocalizationManager
// Initializes with default language "fr" on first call
func GetLocalizationManager() *LocalizationManager {
once.Do(func() {
globalLocManager = &LocalizationManager{
currentLang: "fr",
}
err := globalLocManager.SetLanguage("fr")
if err != nil {
log.Fatalf("Error in localization: %v", err)
}
})
return globalLocManager
}
// SetLanguage loads and sets the catalog for the specified language
// Returns error if language file cannot be loaded
func (lm *LocalizationManager) SetLanguage(lang string) error {
lm.mutex.Lock()
defer lm.mutex.Unlock()
catalog, err := Load(lang)
if err != nil {
return err
}
lm.currentLang = lang
lm.catalog = catalog
return nil
}
// Text retrieves localized text for key with placeholder replacement
// Returns placeholder notation if key not found or catalog not loaded
func (lm *LocalizationManager) Text(key string, args ...any) string {
lm.mutex.RLock()
defer lm.mutex.RUnlock()
if lm.catalog != nil {
return lm.catalog.Text(key, args...)
}
return "⟦" + key + "⟧"
}
// GetCurrentLanguage returns the currently set language code
func (lm *LocalizationManager) GetCurrentLanguage() string {
lm.mutex.RLock()
defer lm.mutex.RUnlock()
return lm.currentLang
}
// GetSupportedLanguages scans assets/interface directory for available .json language files
// Returns slice of language codes and any directory read error
func (lm *LocalizationManager) GetSupportedLanguages() ([]string, error) {
interfaceDir := "assets/interface"
files, err := os.ReadDir(interfaceDir)
if err != nil {
return nil, err
}
var languages []string
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".json") {
lang := strings.TrimSuffix(file.Name(), ".json")
languages = append(languages, lang)
}
}
return languages, nil
}