-
Notifications
You must be signed in to change notification settings - Fork 2
/
i18n.go
275 lines (239 loc) · 7.35 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
// Copyright 2021 Flamego. 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"
"io"
"net/http"
"os"
"path"
"reflect"
"github.com/pkg/errors"
"golang.org/x/text/language"
"unknwon.dev/i18n"
"github.com/flamego/flamego"
)
// CookieOptions contains options for setting HTTP cookies.
type CookieOptions struct {
// Name is the name of the cookie. Default is "lang".
Name string
// Path is the Path attribute of the cookie. Default is "/".
Path string
// Domain is the Domain attribute of the cookie. Default is not set.
Domain string
// MaxAge is the MaxAge attribute of the cookie. Default is math.MaxInt.
MaxAge int
// Secure specifies whether to set Secure for the cookie.
Secure bool
// HTTPOnly specifies whether to set HTTPOnly for the cookie.
HTTPOnly bool
// SameSite is the SameSite attribute of the cookie. Default is
// http.SameSiteLaxMode.
SameSite http.SameSite
}
// Language contains the name and description of a language.
type Language struct {
// Name is the BCP 47 language name, e.g. "en-US".
Name string
// Description is the descriptive name of the language, e.g. "English".
Description string
}
// Options contains options for the i18n.I18n middleware.
type Options struct {
// FileSystem is the interface for supporting any implementation of the
// http.FileSystem.
FileSystem http.FileSystem
// Directory is the primary directory to load locale files. This value is
// ignored when FileSystem is set. Default is "locales".
Directory string
// AppendDirectories is a list of additional directories to load locale files
// for overwriting locale files that are loaded from FileSystem or Directory.
AppendDirectories []string
// Languages is the list of languages to load locale files for.
Languages []Language
// Default is the name of the default language to fall back for missing
// translations. Default is the first element of Languages.
Default string
// NameFormat is the name format of locale files. Default is "locale_%s.ini".
NameFormat string
// QueryParameter is the name of the URL query parameter to accept language
// override. Default is "lang".
QueryParameter string
// Cookie is a set of options for setting HTTP cookies.
Cookie CookieOptions
}
// Locale is the message translator of a language.
type Locale interface {
// Lang returns the BCP 47 language name of the locale.
Lang() string
// Description returns the descriptive name of the locale.
Description() string
// Translate translates the message of the given key. It falls back to use the
// "Default" to translate if the given key does not exist in the current locale.
Translate(key string, args ...interface{}) string
}
type locale struct {
fallback *i18n.Locale
current *i18n.Locale
}
func (l *locale) Lang() string {
return l.current.Lang()
}
func (l *locale) Description() string {
return l.current.Description()
}
func (l *locale) Translate(key string, args ...interface{}) string {
return l.current.TranslateWithFallback(l.fallback, key, args...)
}
// isFile returns true if given path exists as a file (i.e. not a directory).
func isFile(path string) bool {
f, e := os.Stat(path)
if e != nil {
return false
}
return !f.IsDir()
}
// initLocales initializes a locale store with list of provided languages
// loading from http.FileSystem and/or local files. If both `fs` and `dir` are
// provided, only `fs` is considered.
func initLocales(langs []Language, nameFormat string, fs http.FileSystem, dir string, others ...string) (*i18n.Store, language.Matcher, error) {
s := i18n.NewStore()
tags := make([]language.Tag, 0, len(langs))
for _, lang := range langs {
tag, err := language.Parse(lang.Name)
if err != nil {
return nil, nil, errors.Wrapf(err, "parse %q", lang.Name)
}
tags = append(tags, tag)
filename := fmt.Sprintf(nameFormat, lang.Name)
var source io.ReadCloser
if fs != nil {
source, err = fs.Open(filename)
if err != nil {
return nil, nil, errors.Wrap(err, "open from FileSystem")
}
} else {
source, err = os.Open(path.Join(dir, filename))
if err != nil {
return nil, nil, errors.Wrap(err, "open from local")
}
}
otherSources := make([]interface{}, 0, len(others))
for _, other := range others {
otherpath := path.Join(other, filename)
if !isFile(otherpath) {
continue
}
otherSources = append(otherSources, otherpath)
}
_, err = s.AddLocale(lang.Name, lang.Description, source, otherSources...)
if err != nil {
return nil, nil, errors.Wrapf(err, "add locale for %q", lang.Name)
}
}
return s, language.NewMatcher(tags), nil
}
// I18n returns a middleware handler that injects i18n.Locale into the request
// context, which is used for localization.
func I18n(opt Options) flamego.Handler {
parseOptions := func(opts Options) Options {
if opts.Directory == "" {
opts.Directory = "locales"
}
if len(opts.Languages) == 0 {
panic("i18n: no language is specified")
}
if opts.Default == "" {
opts.Default = opts.Languages[0].Name
}
if opts.NameFormat == "" {
opts.NameFormat = "locale_%s.ini"
}
if opts.QueryParameter == "" {
opts.QueryParameter = "lang"
}
if reflect.DeepEqual(opts.Cookie, CookieOptions{}) {
opts.Cookie = CookieOptions{
HTTPOnly: true,
}
}
if opts.Cookie.Name == "" {
opts.Cookie.Name = "lang"
}
if opts.Cookie.SameSite < http.SameSiteDefaultMode || opts.Cookie.SameSite > http.SameSiteNoneMode {
opts.Cookie.SameSite = http.SameSiteLaxMode
}
if opts.Cookie.Path == "" {
opts.Cookie.Path = "/"
}
if opts.Cookie.MaxAge <= 0 {
// TODO: math.MaxInt is only available since Go 1.17, should start using it once
// Go 1.17 becomes the minimum required version.
opts.Cookie.MaxAge = 1<<31 - 1 // = 2147483647
}
return opts
}
opt = parseOptions(opt)
store, matcher, err := initLocales(opt.Languages, opt.NameFormat, opt.FileSystem, opt.Directory, opt.AppendDirectories...)
if err != nil {
panic("i18n: init locales: " + err.Error())
}
fallback, err := store.Locale(opt.Default)
if err != nil {
panic("i18n: get fallback: " + err.Error())
}
return flamego.ContextInvoker(func(c flamego.Context) {
setCookie := func(lang string) {
c.SetCookie(
http.Cookie{
Name: opt.Cookie.Name,
Value: lang,
Path: opt.Cookie.Path,
Domain: opt.Cookie.Domain,
MaxAge: opt.Cookie.MaxAge,
Secure: opt.Cookie.Secure,
HttpOnly: opt.Cookie.HTTPOnly,
SameSite: opt.Cookie.SameSite,
},
)
}
// 1. Check URL query parameter
lang := c.Query(opt.QueryParameter)
if lang != "" {
setCookie(lang)
}
// 2. Check cookie
if lang == "" {
lang = c.Cookie(opt.Cookie.Name)
}
// 3. Check the first element in the "Accept-Language" header
if lang == "" {
tags, _, _ := language.ParseAcceptLanguage(c.Request().Header.Get("Accept-Language"))
tag, _, confidence := matcher.Match(tags...)
if confidence != language.No {
lang = tag.String()
setCookie(lang)
}
}
// 4. Fall back to default
if lang == "" {
lang = opt.Default
setCookie(lang)
}
var l Locale
current, err := store.Locale(lang)
if err != nil {
if err != i18n.ErrLocalNotFound {
panic("i18n: get locale: " + err.Error())
}
l = fallback
} else {
l = &locale{
fallback: fallback,
current: current,
}
}
c.MapTo(l, (*Locale)(nil))
})
}