/
i118.go
103 lines (85 loc) · 2.1 KB
/
i118.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
package i118Utils
import (
"encoding/json"
"github.com/easysoft/zentaoatf/res"
"github.com/easysoft/zentaoatf/src/utils/common"
constant "github.com/easysoft/zentaoatf/src/utils/const"
fileUtils "github.com/easysoft/zentaoatf/src/utils/file"
"golang.org/x/text/language"
"golang.org/x/text/message"
"io/ioutil"
)
var I118Prt *message.Printer
func Sprintf(tmpl string, params ...interface{}) (ret string) {
ret = I118Prt.Sprintf(tmpl, params...)
return
}
func InitI118(lang string) {
//var once sync.Once
//once.Do(func() {
isRelease := commonUtils.IsRelease()
var langRes string
if lang == constant.LanguageEN {
langRes = constant.EnRes
} else {
langRes = constant.ZhRes
}
if isRelease {
data, _ := res.Asset(langRes)
InitResFromAsset(data)
} else {
InitRes(langRes)
}
if lang == "zh" {
I118Prt = message.NewPrinter(language.SimplifiedChinese)
} else {
I118Prt = message.NewPrinter(language.AmericanEnglish)
}
//})
}
type I18n struct {
Language string `json:"language"`
Messages []Message `json:"messages"`
}
type Message struct {
Id string `json:"id"`
Message string `json:"message,omitempty"`
Translation string `json:"translation,omitempty"`
}
func Check(e error) {
if e != nil {
panic(e)
}
}
func ReadI18nJson(file string) string {
b, err := ioutil.ReadFile(file)
Check(err)
str := string(b)
return str
}
func InitRes(jsonPath string) {
if !fileUtils.FileExist(jsonPath) { // for debug with ide only, run unit test in another project dir
if commonUtils.IsWin() {
jsonPath = "C:\\dev\\project\\go\\ztf\\" + jsonPath
} else {
jsonPath = "/Users/aaron/rd/project/zentao/go/ztf/" + jsonPath
}
}
var i18n I18n
str := ReadI18nJson(jsonPath)
json.Unmarshal([]byte(str), &i18n)
msgArr := i18n.Messages
tag := language.MustParse(i18n.Language)
for _, e := range msgArr {
message.SetString(tag, e.Id, e.Translation)
}
}
func InitResFromAsset(bytes []byte) {
var i18n I18n
json.Unmarshal(bytes, &i18n)
msgArr := i18n.Messages
tag := language.MustParse(i18n.Language)
for _, e := range msgArr {
message.SetString(tag, e.Id, e.Translation)
}
}