/
localizer.go
64 lines (49 loc) · 940 Bytes
/
localizer.go
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
package intl
import (
"embed"
"fmt"
"sync"
"github.com/pelletier/go-toml"
)
var lz *localizer
func Init(defaultLocale string, localesDir embed.FS) {
if lz != nil {
return
}
lz = &localizer{locale: defaultLocale, localesDir: localesDir}
loadLocale()
}
type localizer struct {
locale string
localeTree *toml.Tree
localesDir embed.FS
mu sync.Mutex
}
func loadLocale() {
var err error
localeFileBytes, err := lz.localesDir.ReadFile(fmt.Sprintf("locales/%s.toml", lz.locale))
if err != nil {
panic(err)
}
lz.localeTree, err = toml.LoadBytes(localeFileBytes)
if err != nil {
panic(err)
}
}
func SetLocale(locale string) {
lz.mu.Lock()
defer lz.mu.Unlock()
lz.locale = locale
loadLocale()
}
func GetLocale() string {
return lz.locale
}
func Localize(key string) string {
if value := lz.localeTree.Get(key); value != nil {
if s, ok := value.(string); ok {
return s
}
}
return ""
}