-
Notifications
You must be signed in to change notification settings - Fork 0
/
translator.go
123 lines (91 loc) · 2.39 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package i18n
import (
"context"
"io/fs"
"net/http"
"sync"
"github.com/pkg/errors"
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/message/catalog"
"github.com/derfenix/goi18n/internal"
)
var defaultLanguage = language.Russian
var (
initOnce sync.Once
builder *catalog.Builder
supportedLanguages []language.Tag
supportedLanguagesMap = map[string]struct{}{}
)
func NewExternalLoader(baseURL string, header http.Header) *internal.ExternalLoader {
return internal.NewExternalLoader(baseURL, header)
}
func NewExternalLoaderWithClient(baseURL string, header http.Header, client *http.Client) *internal.ExternalLoader {
return internal.NewExternalLoaderWithClient(baseURL, header, client)
}
type Translatable interface {
Translate(ctx context.Context) string
}
func TryTranslate(ctx context.Context, obj interface{}) (string, bool) {
if translatable, ok := obj.(Translatable); ok {
return translatable.Translate(ctx), true
}
return "", false
}
func Init(fs fs.ReadDirFS) error {
var err error
initOnce.Do(func() {
if builder != nil {
return
}
initCatalog, err := internal.InitBuilder(fs)
if err != nil {
err = errors.Wrap(err, "init catalog")
return
}
builder = initCatalog
// Fill the local cache
GetLanguages()
})
return err
}
func GetPrinter(lang language.Tag) *message.Printer {
_ = GetLanguages()
base, _ := lang.Base()
if _, ok := supportedLanguagesMap[lang.String()]; !ok {
if _, ok = supportedLanguagesMap[base.String()]; !ok {
lang = defaultLanguage
}
}
p := message.NewPrinter(lang, message.Catalog(builder))
return p
}
func GetLanguages() []language.Tag {
if supportedLanguages == nil {
if builder == nil {
return nil
}
supportedLanguages = builder.Languages()
for idx := range supportedLanguages {
supportedLanguagesMap[supportedLanguages[idx].String()] = struct{}{}
base, _ := supportedLanguages[idx].Base()
supportedLanguagesMap[base.String()] = struct{}{}
}
}
return supportedLanguages
}
func RefreshTranslations() error {
if builder == nil {
return nil
}
if err := internal.RefreshTranslations(builder); err != nil {
return errors.WithMessage(err, "refresh translations")
}
return nil
}
func SetExternalBuilder(b func(builder *catalog.Builder) error) {
internal.SetExtendBuilder(b)
}
func SetExternalLoader(loader internal.Loader) {
internal.SetExternalLoader(loader)
}