github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/pkg/utils/i118/i118.go (about) 1 package i118Utils 2 3 import ( 4 "encoding/json" 5 "os" 6 "path/filepath" 7 8 zd "github.com/easysoft/zendata" 9 constant "github.com/easysoft/zendata/internal/pkg/const" 10 commonUtils "github.com/easysoft/zendata/pkg/utils/common" 11 "github.com/easysoft/zendata/pkg/utils/vari" 12 "golang.org/x/text/language" 13 "golang.org/x/text/message" 14 ) 15 16 var I118Prt *message.Printer 17 18 func InitI118(lang string) { 19 //var once sync.Once 20 //once.Do(func() { 21 isRelease := commonUtils.IsRelease() 22 23 var langRes string 24 if lang == constant.LanguageEN { 25 langRes = constant.EnRes 26 } else { 27 langRes = constant.ZhRes 28 } 29 30 if isRelease { 31 data, _ := zd.ReadResData(langRes) 32 InitResFromAsset(data) 33 } else { 34 InitRes(filepath.Join(vari.WorkDir, langRes)) 35 } 36 37 if lang == "zh" { 38 I118Prt = message.NewPrinter(language.SimplifiedChinese) 39 } else { 40 I118Prt = message.NewPrinter(language.AmericanEnglish) 41 } 42 //}) 43 } 44 45 type I18n struct { 46 Language string `json:"language"` 47 Messages []Message `json:"messages"` 48 } 49 50 type Message struct { 51 Id string `json:"id"` 52 Message string `json:"message,omitempty"` 53 Translation string `json:"translation,omitempty"` 54 } 55 56 func Check(e error) { 57 if e != nil { 58 panic(e) 59 } 60 } 61 func ReadI18nJson(file string) string { 62 b, err := os.ReadFile(file) 63 Check(err) 64 str := string(b) 65 return str 66 67 } 68 69 func InitRes(jsonPath string) { 70 var i18n I18n 71 str := ReadI18nJson(jsonPath) 72 json.Unmarshal([]byte(str), &i18n) 73 74 msgArr := i18n.Messages 75 tag := language.MustParse(i18n.Language) 76 77 for _, e := range msgArr { 78 message.SetString(tag, e.Id, e.Translation) 79 } 80 } 81 82 func InitResFromAsset(bytes []byte) { 83 var i18n I18n 84 json.Unmarshal(bytes, &i18n) 85 86 msgArr := i18n.Messages 87 tag := language.MustParse(i18n.Language) 88 89 for _, e := range msgArr { 90 message.SetString(tag, e.Id, e.Translation) 91 } 92 } 93 94 func Sprintf(key string, args ...interface{}) (ret string) { 95 ret = I118Prt.Sprintf(key, args...) 96 97 return 98 }