Skip to content

Commit

Permalink
add i18n package
Browse files Browse the repository at this point in the history
  • Loading branch information
UlricQin committed Sep 14, 2021
1 parent d58c579 commit 25b5d80
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions i18n/i18n.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package i18n

import (
"encoding/json"
"fmt"
"path"
"strings"

"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/message/catalog"

"github.com/toolkits/pkg/file"
"github.com/toolkits/pkg/runner"
)

var (
catalogs = make(map[string]*catalog.Builder)
printers = make(map[string]*message.Printer)
)

// Init will init i18n support via input language.
func Init(dictPath ...string) {
dp := path.Join(runner.Cwd, "etc", "i18n.json")
if len(dictPath) > 0 {
dp = dictPath[0]
}

DictFileRegister(dp)

// en for default
printers[""] = message.NewPrinter(langTag("en"))
printers["en"] = message.NewPrinter(langTag("en"))
}

func DictFileRegister(filePath string) {
if !file.IsExist(filePath) {
// fmt.Printf("i18n config file %s not found. donot worry, we'll use default configuration\n", filePath)
return
}

content, err := file.ToTrimString(filePath)
if err != nil {
fmt.Printf("read i18n config file %s fail: %s\n", filePath, err)
return
}

m := make(map[string]map[string]string)
err = json.Unmarshal([]byte(content), &m)
if err != nil {
fmt.Printf("parse i18n config file %s fail: %s\n", filePath, err)
return
}

DictRegister(m)
}

func DictRegister(m map[string]map[string]string) {
for lang, dict := range m {
tag := langTag(lang)
if tag == language.English {
continue
}

cata := catalog.NewBuilder()
for k, v := range dict {
cata.SetString(tag, k, v)
}

catalogs[lang] = cata
printers[lang] = message.NewPrinter(tag, message.Catalog(cata))
}
}

func langTag(l string) language.Tag {
switch strings.ToLower(l) {
case "zh", "cn":
return language.Chinese
default:
return language.English
}
}

// Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(lang, format string, a ...interface{}) string {
return printers[lang].Sprintf(format, a...)
}

0 comments on commit 25b5d80

Please sign in to comment.