-
Notifications
You must be signed in to change notification settings - Fork 0
/
goi18n.go
41 lines (33 loc) · 965 Bytes
/
goi18n.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
package goi18n
import (
"errors"
"github.com/BurntSushi/toml"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/spf13/cast"
"golang.org/x/text/language"
)
type Engine struct {
loader *i18n.Localizer
}
func New(languege string, path string) (*Engine, error) {
lan := language.Make(languege)
if lan.IsRoot() {
return nil, errors.New("language is not supported")
}
bundle := i18n.NewBundle(lan)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
bundle.MustLoadMessageFile(path)
eg := &Engine{
loader: i18n.NewLocalizer(bundle, lan.String()),
}
return eg, nil
}
// 根据(id)key获取value
// 支持模板数据填充,非模版数据 templateData为nil即可
func (e *Engine) Get(id interface{}, templateData map[string]interface{}) (string, error) {
idStr := cast.ToString(id)
if idStr == "" {
return "", errors.New("id is empty")
}
return e.loader.Localize(&i18n.LocalizeConfig{MessageID: idStr, TemplateData: templateData})
}