-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
i18n.go
284 lines (252 loc) · 9.33 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package i18n
import (
"fmt"
"io/fs"
"path/filepath"
"sort"
"strings"
"github.com/gobuffalo/buffalo"
"github.com/nicksnyder/go-i18n/i18n"
"github.com/nicksnyder/go-i18n/i18n/language"
"github.com/nicksnyder/go-i18n/i18n/translation"
)
// LanguageExtractor can be implemented for custom finding of search
// languages. This can be useful if you want to load a user's language
// from something like a database. See Middleware() for more information
// on how the default implementation searches for languages.
type LanguageExtractor func(LanguageExtractorOptions, buffalo.Context) []string
// LanguageExtractorOptions is a map of options for a LanguageExtractor.
type LanguageExtractorOptions map[string]interface{}
// Translator for handling all your i18n needs.
type Translator struct {
// FS that contains the files
FS fs.FS
// DefaultLanguage - default is passed as a parameter on New.
DefaultLanguage string
// HelperName - name of the view helper. default is "t"
HelperName string
// LanguageExtractors - a sorted list of user language extractors.
LanguageExtractors []LanguageExtractor
// LanguageExtractorOptions - a map with options to give to LanguageExtractors.
LanguageExtractorOptions LanguageExtractorOptions
}
// Load translations from the t.FS
func (t *Translator) Load() error {
return fs.WalkDir(t.FS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
b, err := fs.ReadFile(t.FS, path)
if err != nil {
return fmt.Errorf("unable to read locale file %s: %v", path, err)
}
base := filepath.Base(path)
dir := filepath.Dir(path)
// Add a prefix to the loaded string, to avoid collision with an ISO lang code
err = i18n.ParseTranslationFileBytes(fmt.Sprintf("%sbuff%s", dir, base), b)
if err != nil {
return fmt.Errorf("unable to parse locale file %s: %v", base, err)
}
return nil
})
}
// AddTranslation directly, without using a file. This is useful if you wish to load translations
// from a database, instead of disk.
func (t *Translator) AddTranslation(lang *language.Language, translations ...translation.Translation) {
i18n.AddTranslation(lang, translations...)
}
// New Translator. Requires a fs.FS that points to the location
// of the translation files, as well as a default language. This will
// also call t.Load() and load the translations from disk.
func New(fsys fs.FS, language string) (*Translator, error) {
t := &Translator{
FS: fsys,
DefaultLanguage: language,
HelperName: "t",
LanguageExtractorOptions: LanguageExtractorOptions{
"CookieName": "lang",
"SessionName": "lang",
"URLPrefixName": "lang",
},
LanguageExtractors: []LanguageExtractor{
CookieLanguageExtractor,
SessionLanguageExtractor,
HeaderLanguageExtractor,
},
}
return t, t.Load()
}
// Middleware for loading the translations for the language(s)
// selected. By default languages are loaded in the following order:
//
// Cookie - "lang"
// Session - "lang"
// Header - "Accept-Language"
// Default - "en-US"
//
// These values can be changed on the Translator itself. In development
// model the translation files will be reloaded on each request.
func (t *Translator) Middleware() buffalo.MiddlewareFunc {
return func(next buffalo.Handler) buffalo.Handler {
return func(c buffalo.Context) error {
// in development reload the translations
if c.Value("env").(string) == "development" {
err := t.Load()
if err != nil {
return err
}
}
// set languages in context, if not set yet
if langs := c.Value("languages"); langs == nil {
c.Set("languages", t.extractLanguage(c))
}
// set translator
if T := c.Value("T"); T == nil {
langs := c.Value("languages").([]string)
T, err := i18n.Tfunc(langs[0], langs[1:]...)
if err != nil {
c.Logger().Warn(err)
c.Logger().Warn("Your locale files are probably empty or missing")
}
c.Set("T", T)
}
// set up the helper function for the views:
c.Set(t.HelperName, func(s string, i ...interface{}) string {
return t.Translate(c, s, i...)
})
return next(c)
}
}
}
// Translate returns the translation of the string identified by translationID.
//
// See https://github.com/gobuffalo/i18n-mw/internal/go-i18n
//
// If there is no translation for translationID, then the translationID itself is returned.
// This makes it easy to identify missing translations in your app.
//
// If translationID is a non-plural form, then the first variadic argument may be a map[string]interface{}
// or struct that contains template data.
//
// If translationID is a plural form, the function accepts two parameter signatures
// 1. T(count int, data struct{})
// The first variadic argument must be an integer type
// (int, int8, int16, int32, int64) or a float formatted as a string (e.g. "123.45").
// The second variadic argument may be a map[string]interface{} or struct{} that contains template data.
// 2. T(data struct{})
// data must be a struct{} or map[string]interface{} that contains a Count field and the template data,
// Count field must be an integer type (int, int8, int16, int32, int64)
// or a float formatted as a string (e.g. "123.45").
func (t *Translator) Translate(c buffalo.Context, translationID string, args ...interface{}) string {
T := c.Value("T").(i18n.TranslateFunc)
return T(translationID, args...)
}
// TranslateWithLang returns the translation of the string identified by translationID, for the given language.
// See Translate for further details.
func (t *Translator) TranslateWithLang(lang, translationID string, args ...interface{}) (string, error) {
T, err := i18n.Tfunc(lang)
if err != nil {
return "", err
}
return T(translationID, args...), nil
}
// AvailableLanguages gets the list of languages provided by the app.
func (t *Translator) AvailableLanguages() []string {
lt := i18n.LanguageTags()
sort.Strings(lt)
return lt
}
// Refresh updates the context, reloading translation functions.
// It can be used after language change, to be able to use translation functions
// in the new language (for a flash message, for instance).
func (t *Translator) Refresh(c buffalo.Context, newLang string) {
langs := []string{newLang}
langs = append(langs, t.extractLanguage(c)...)
// Refresh languages
c.Set("languages", langs)
T, err := i18n.Tfunc(langs[0], langs[1:]...)
if err != nil {
c.Logger().Warn(err)
c.Logger().Warn("Your locale files are probably empty or missing")
}
// Refresh translation engine
c.Set("T", T)
}
func (t *Translator) extractLanguage(c buffalo.Context) []string {
langs := []string{}
for _, extractor := range t.LanguageExtractors {
langs = append(langs, extractor(t.LanguageExtractorOptions, c)...)
}
// Add default language, even if no language extractor is defined
langs = append(langs, t.DefaultLanguage)
return langs
}
// CookieLanguageExtractor is a LanguageExtractor implementation, using a cookie.
func CookieLanguageExtractor(o LanguageExtractorOptions, c buffalo.Context) []string {
langs := make([]string, 0)
// try to get the language from a cookie:
if cookieName := o["CookieName"].(string); cookieName != "" {
if cookie, err := c.Request().Cookie(cookieName); err == nil {
if cookie.Value != "" {
langs = append(langs, cookie.Value)
}
}
} else {
c.Logger().Error("i18n middleware: \"CookieName\" is not defined in LanguageExtractorOptions")
}
return langs
}
// SessionLanguageExtractor is a LanguageExtractor implementation, using a session.
func SessionLanguageExtractor(o LanguageExtractorOptions, c buffalo.Context) []string {
langs := make([]string, 0)
// try to get the language from the session
if sessionName := o["SessionName"].(string); sessionName != "" {
if s := c.Session().Get(sessionName); s != nil {
langs = append(langs, s.(string))
}
} else {
c.Logger().Error("i18n middleware: \"SessionName\" is not defined in LanguageExtractorOptions")
}
return langs
}
// HeaderLanguageExtractor is a LanguageExtractor implementation, using a HTTP Accept-Language
// header.
func HeaderLanguageExtractor(o LanguageExtractorOptions, c buffalo.Context) []string {
langs := make([]string, 0)
// try to get the language from a header:
acceptLang := c.Request().Header.Get("Accept-Language")
if acceptLang != "" {
langs = append(langs, parseAcceptLanguage(acceptLang)...)
}
return langs
}
// URLPrefixLanguageExtractor is a LanguageExtractor implementation, using a prefix in the URL.
func URLPrefixLanguageExtractor(o LanguageExtractorOptions, c buffalo.Context) []string {
langs := make([]string, 0)
// try to get the language from an URL prefix:
if urlPrefixName := o["URLPrefixName"].(string); urlPrefixName != "" {
paramLang := c.Param(urlPrefixName)
if paramLang != "" && strings.HasPrefix(c.Request().URL.Path, fmt.Sprintf("/%s", paramLang)) {
langs = append(langs, paramLang)
}
} else {
c.Logger().Error("i18n middleware: \"URLPrefixName\" is not defined in LanguageExtractorOptions")
}
return langs
}
// Inspired from https://siongui.github.io/2015/02/22/go-parse-accept-language/
// Parse an Accept-Language string to get usable lang values for i18n system
func parseAcceptLanguage(acptLang string) []string {
var lqs []string
langQStrs := strings.Split(acptLang, ",")
for _, langQStr := range langQStrs {
trimedLangQStr := strings.Trim(langQStr, " ")
langQ := strings.Split(trimedLangQStr, ";")
lq := langQ[0]
lqs = append(lqs, lq)
}
return lqs
}