-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlanguage.go
117 lines (98 loc) · 2.24 KB
/
language.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"embed"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"github.com/jeandeaual/go-locale"
)
//go:embed languages/*
var langDatas embed.FS
var MYLANG = "en"
type Language struct {
Data map[string]map[string]string
}
func NewLanguage() *Language {
var l = Language{Data: make(map[string]map[string]string)}
l.SetLang()
l.Load()
return &l
}
func (l *Language) UText(langText string) string {
translated := langText
if lang, ok := l.Data[langText]; ok {
if text, ok := lang[MYLANG]; ok {
translated = text
}
} else {
if MYLANG != "en" {
fmt.Printf("unmatch:\"%s\" \"%s\"\n", langText, MYLANG)
}
}
return translated
}
func (l *Language) UTextWithLangCode(langText, lcode string) string {
translated := langText
if lang, ok := l.Data[langText]; ok {
if text, ok := lang[lcode]; ok {
translated = text
}
} else {
if lcode != "en" {
fmt.Printf("unmatch:\"%s\" \"%s\"\n", langText, lcode)
return ""
}
}
return translated
}
func (l *Language) SetLang() {
if lang := os.Getenv("MYLANG"); lang != "" {
fmt.Println("using user lang:", lang)
MYLANG = lang
return
}
userLanguage, err := locale.GetLanguage()
if err == nil {
fmt.Println("Current Language:", userLanguage)
MYLANG = userLanguage
}
}
func (l *Language) Load() {
files, err := langDatas.ReadDir("languages")
if err != nil {
log.Fatal(err)
}
languages := make([]map[string]map[string]string, 0)
for _, file := range files {
if filepath.Ext(file.Name()) == ".json" {
fmt.Println("load language:", file.Name())
data, err := langDatas.ReadFile("languages/" + file.Name())
if err != nil {
log.Println("Error reading file:", err)
continue
}
languageJson := make(map[string]map[string]string)
err = json.Unmarshal(data, &languageJson)
if err != nil {
log.Println("Error unmarshaling JSON:", err)
continue
}
languages = append(languages, languageJson)
}
}
l.combineLanguages(languages)
}
func (l *Language) combineLanguages(languages []map[string]map[string]string) {
for _, language := range languages {
for key, value := range language {
if _, ok := l.Data[key]; !ok {
l.Data[key] = make(map[string]string)
}
for k, v := range value {
l.Data[key][k] = v
}
}
}
}