-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.go
42 lines (32 loc) · 1.03 KB
/
translator.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
package huner
import (
"fmt"
"strings"
"github.com/BurntSushi/toml"
"github.com/kamva/hexa"
"github.com/kamva/hexa/hexatranslator"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
type TranslateOpts struct {
Files []string
FallbackLangs []string
}
// NewTranslator returns a new translator service.
func NewTranslator(pathPrefix string, cfg TranslateOpts) hexa.Translator {
defaultLang := language.English
if len(cfg.FallbackLangs) >= 1 {
defaultLang = language.MustParse(cfg.FallbackLangs[0])
}
bundle := i18n.NewBundle(defaultLang)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
loadLangFiles(bundle, pathPrefix, cfg.Files)
localizer := i18n.NewLocalizer(bundle, cfg.FallbackLangs...)
return hexatranslator.NewI18nDriver(bundle, localizer, cfg.FallbackLangs)
}
func loadLangFiles(bundle *i18n.Bundle, prefix string, files []string) {
for _, file := range files {
f := fmt.Sprintf("%s/%s.toml", strings.TrimRight(prefix, "/"), strings.Trim(file, "/"))
bundle.MustLoadMessageFile(f)
}
}