-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi18n.go
185 lines (156 loc) · 3.71 KB
/
i18n.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package i18n
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/BurntSushi/toml"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
)
type LanguageKey struct{}
type Localized = i18n.LocalizeConfig
type UnmarshalFunc = i18n.UnmarshalFunc
type LanguageProvider[T, U any] func(source T, key U) language.Tag
type Message interface {
~string | Localized | ~*Localized
}
type I18n struct {
bundle *i18n.Bundle
defaultlang language.Tag
localizes map[language.Tag]*i18n.Localizer
loaders []Loader
languageKey any
}
func (g *I18n) setDefaultLang(lang language.Tag) {
g.defaultlang = lang
g.bundle = i18n.NewBundle(lang)
}
func (g *I18n) addLoader(loader Loader) {
result, err := loader.Load()
if err != nil {
panic(err)
}
for format, fn := range result.Funcs {
g.bundle.RegisterUnmarshalFunc(format, fn)
}
for _, entry := range result.Entries {
g.setLocalizer(entry.Tag)
g.bundle.MustParseMessageFileBytes(entry.Bytes, entry.Name)
}
}
func (g *I18n) tr(ctx context.Context, p any) (string, error) {
value := ctx.Value(LanguageKey{})
tag, ok := value.(language.Tag)
if !ok {
tag = g.defaultlang
}
lr := g.getLocalizer(tag)
var config *i18n.LocalizeConfig
switch t := p.(type) {
case string:
config = &i18n.LocalizeConfig{MessageID: t}
case i18n.LocalizeConfig:
config = &t
case *i18n.LocalizeConfig:
config = t
default:
return "", fmt.Errorf("unsupported param %T", p)
}
translated, err := lr.Localize(config)
if err != nil || len(translated) == 0 {
return config.MessageID, err
}
return translated, nil
}
func getUnmarshaler(format string) UnmarshalFunc {
switch format {
case "json":
return json.Unmarshal
case "toml":
return toml.Unmarshal
case "yaml":
return yaml.Unmarshal
default:
return nil
}
}
func (g *I18n) setLocalizer(lang language.Tag) {
if _, ok := g.localizes[lang]; ok {
return
}
if g.localizes == nil {
g.localizes = make(map[language.Tag]*i18n.Localizer)
}
langs := []string{lang.String()}
if lang != g.defaultlang {
langs = append(langs, g.defaultlang.String())
}
g.localizes[lang] = i18n.NewLocalizer(g.bundle, langs...)
}
func (g *I18n) getLocalizer(lang language.Tag) *i18n.Localizer {
if lr, ok := g.localizes[lang]; ok {
return lr
}
return g.localizes[g.defaultlang]
}
var (
g *I18n
languageProvider any
)
func Initialize(opts ...Option) *I18n {
if g != nil {
return g
}
g = new(I18n)
for _, opt := range opts {
opt(g)
}
if g.defaultlang.IsRoot() {
g.setDefaultLang(language.English)
} else {
g.setDefaultLang(g.defaultlang)
}
for _, loader := range g.loaders {
g.addLoader(loader)
}
if g.languageKey == nil {
g.languageKey = "Accept-Language"
}
g.setLocalizer(g.defaultlang)
return g
}
// Handler returns http.Handler. It can be using a middleware...
func (g *I18n) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tag := g.defaultlang
if p, ok := languageProvider.(LanguageProvider[*http.Request, string]); ok {
tag = p(r, g.languageKey.(string))
}
r = r.WithContext(context.WithValue(r.Context(), LanguageKey{}, tag))
next.ServeHTTP(w, r)
})
}
// Tr translate messageId to target language
//
// Example:
//
// Tr(ctx, "hello")
// Tr(ctx, &Localized{
// Message: "HelloName",
// TemplateData: map[string]string{
// "Name": "I18n",
// },
// })
func Tr[T Message](ctx context.Context, message T) (string, error) {
if g == nil {
panic("i18n uninitialized, using i18n.Initialize(opts...) to init")
}
return g.tr(ctx, message)
}
// MustTr called Tr but ignore error
func MustTr[T Message](ctx context.Context, message T) string {
translated, _ := Tr(ctx, message)
return translated
}