-
Notifications
You must be signed in to change notification settings - Fork 8
/
locale.go
69 lines (59 loc) · 1.19 KB
/
locale.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
65
66
67
68
69
package main
import (
"embed"
"fmt"
"io"
"slices"
"github.com/BurntSushi/toml"
)
//go:embed lang
var langFS embed.FS
var (
langTable = make(map[string]any)
)
func DelayInitializeLocale() error {
return SetLocale(defaultLocaleName())
}
func SetLocale(lan string) error {
if !slices.Contains([]string{"zh-CN", "en-US", "zh-TW"}, lan) {
lan = "en-US"
}
langFile := fmt.Sprint("lang/", lan, ".toml")
fd, err := langFS.Open(langFile)
if err != nil {
return err
}
defer fd.Close()
if _, err := toml.NewDecoder(fd).Decode(&langTable); err != nil {
return err
}
return nil
}
func DefaultLocaleName() string {
return defaultLocaleName()
}
func LoadString(k string) string {
if v, ok := langTable[k]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
func LoadStringList(ks ...string) []string {
msgList := make([]string, 0)
for _, k := range ks {
if v, ok := langTable[k]; ok {
if s, ok := v.(string); ok {
msgList = append(msgList, s)
}
}
}
return msgList
}
func Fprintf(w io.Writer, format string, a ...any) (n int, err error) {
if localeFmt := LoadString(format); len(localeFmt) != 0 {
format = localeFmt
}
return fmt.Fprintf(w, format, a...)
}