-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtranslator.go
86 lines (71 loc) · 1.99 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
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
// Copyright 2020 CleverGo. All rights reserved.
// Use of this source code is governed by a MIT style license that can be found
// in the LICENSE file.
package i18n
import (
"fmt"
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/message/catalog"
)
// Option for appling on translatiors.
type Option func(ts *Translators)
// Fallback is an option to change fallback language of translators.
func Fallback(fallback string) Option {
return func(ts *Translators) {
ts.fallback = fallback
}
}
// Translators is a collections of translator.
type Translators struct {
*catalog.Builder
fallback string
}
// New returns a translators.
func New(opts ...Option) *Translators {
ts := &Translators{
fallback: "en",
}
for _, opt := range opts {
opt(ts)
}
ts.Builder = catalog.NewBuilder(catalog.Fallback(language.Make(ts.fallback)))
return ts
}
// MatchTranslator returns the matched translator of the given language.
func (ts *Translators) MatchTranslator(langs ...string) *Translator {
tag, _ := language.MatchStrings(ts.Matcher(), langs...)
p := message.NewPrinter(tag, message.Catalog(ts))
return NewTranslator(p)
}
// Translations is a map that mapping from language to translations.
type Translations map[string]Translation
// Translation is a key-value pair.
type Translation map[string]string
// Import imports translations from the given store.
func (ts *Translators) Import(store Store) error {
translations, err := store.Get()
if err != nil {
return err
}
for lang, translation := range translations {
tag := language.Make(lang)
if tag.IsRoot() {
return fmt.Errorf("unsupported language code: %s", lang)
}
for key, msg := range translation {
if err = ts.SetString(tag, key, msg); err != nil {
return err
}
}
}
return nil
}
// Translator is a wrapper of message.Printer.
type Translator struct {
*message.Printer
}
// NewTranslator returns a new Translator.
func NewTranslator(printer *message.Printer) *Translator {
return &Translator{printer}
}