-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathi18n.go
399 lines (373 loc) · 16.4 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package valix
import (
"encoding/json"
"golang.org/x/text/language"
"net/http"
"strings"
)
var (
DefaultI18nProvider I18n = &defaultI18nProvider{}
)
// DefaultLanguage is the default language used by the default I18nProvider
//
// Languages provided are "de", "en", "es", "fr" & "it"
var DefaultLanguage = "en"
// DefaultRegion is the default region used by the default I18nProvider
var DefaultRegion = ""
// DefaultFallbackLanguages is a map of language codes with their fallback language code
var DefaultFallbackLanguages = map[string]string{}
// I18n interface for supporting i18n (internationalisation) in valix -
// used to provide I18nContext interfaces upon request by the Validators
type I18n interface {
ContextFromRequest(r *http.Request) I18nContext
DefaultContext() I18nContext
}
// I18nContext is the interface passed around during validation that provides translations of
// messages, message formats and individual word tokens
type I18nContext interface {
TranslateMessage(msg string) string
TranslateFormat(format string, a ...interface{}) string
TranslateToken(token string) string
Language() string
Region() string
}
type defaultI18nContext struct {
lang string
region string
}
func newDefaultI18nContext(lang string, region string) I18nContext {
return &defaultI18nContext{
lang: defaultLanguage(lang),
region: strings.ToUpper(region),
}
}
func defaultLanguage(lang string) string {
result := strings.ToLower(lang)
if result != "en" && result != "de" && result != "es" && result != "fr" && result != "it" {
if fb, ok := DefaultFallbackLanguages[result]; ok {
result = strings.ToLower(fb)
} else {
result = strings.ToLower(DefaultLanguage)
}
} else {
return result
}
if result != "en" && result != "de" && result != "es" && result != "fr" && result != "it" {
result = "en"
}
return result
}
func (d *defaultI18nContext) TranslateMessage(msg string) string {
return DefaultTranslator.TranslateMessage(d.lang, d.region, msg)
}
func (d *defaultI18nContext) TranslateFormat(format string, a ...interface{}) string {
return DefaultTranslator.TranslateFormat(d.lang, d.region, format, a...)
}
func (d *defaultI18nContext) TranslateToken(token string) string {
return DefaultTranslator.TranslateToken(d.lang, d.region, token)
}
func (d *defaultI18nContext) Language() string {
return d.lang
}
func (d *defaultI18nContext) Region() string {
return d.region
}
func (d *defaultI18nContext) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"tokens": internalTokens,
"messages": internalMessages,
"formats": internalFormats,
}
return json.Marshal(m)
}
type defaultI18nProvider struct{}
func (i *defaultI18nProvider) ContextFromRequest(r *http.Request) I18nContext {
tags, _, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
useLang := DefaultLanguage
useRegion := DefaultRegion
if err == nil {
for _, tag := range tags {
baseLang, _ := tag.Base()
if baseLang.String() == defaultLanguage(baseLang.String()) {
useLang = baseLang.String()
_, _, rawRgn := tag.Raw()
if rawRgn.String() != "ZZ" {
useRegion = rawRgn.String()
}
break
}
}
}
return newDefaultI18nContext(useLang, useRegion)
}
func (i *defaultI18nProvider) DefaultContext() I18nContext {
return newDefaultI18nContext(DefaultLanguage, DefaultRegion)
}
var fallbackI18nProvider I18n = &defaultI18nProvider{}
func obtainI18nProvider() I18n {
if DefaultI18nProvider != nil {
return DefaultI18nProvider
}
return fallbackI18nProvider
}
var fallbackI18nContext I18nContext = &defaultI18nContext{lang: "en"}
// used by ValidatorContext and constraints to ensure they never try to use a nil I18nContext
func obtainI18nContext(i18nCtx I18nContext) I18nContext {
if i18nCtx != nil {
return i18nCtx
}
result := obtainI18nProvider().DefaultContext()
if result != nil {
return result
}
return fallbackI18nContext
}
// used by defaultI18nContext.MarshalJSON - to allow listing of translation reference
// also as a kind of double-entry bookkeeping to ensure everything has been translated into TranslationsMessages
var internalMessages = map[string]string{
msgUnableToDecode: msgUnableToDecode,
msgNotJsonNull: msgNotJsonNull,
msgNotJsonArray: msgNotJsonArray,
msgNotJsonObject: msgNotJsonObject,
msgExpectedJsonArray: msgExpectedJsonArray,
msgExpectedJsonObject: msgExpectedJsonObject,
msgErrorReading: msgErrorReading,
msgErrorUnmarshall: msgErrorUnmarshall,
msgRequestBodyEmpty: msgRequestBodyEmpty,
msgUnableToDecodeRequest: msgUnableToDecodeRequest,
msgRequestBodyNotJsonNull: msgRequestBodyNotJsonNull,
msgRequestBodyNotJsonArray: msgRequestBodyNotJsonArray,
msgRequestBodyNotJsonObject: msgRequestBodyNotJsonObject,
msgRequestBodyExpectedJsonArray: msgRequestBodyExpectedJsonArray,
msgRequestBodyExpectedJsonObject: msgRequestBodyExpectedJsonObject,
msgArrayElementMustBeObject: msgArrayElementMustBeObject,
msgArrayElementMustNotBeNull: msgArrayElementMustNotBeNull,
msgMissingProperty: msgMissingProperty,
msgUnwantedProperty: msgUnwantedProperty,
msgUnknownProperty: msgUnknownProperty,
msgOnlyProperty: msgOnlyProperty,
msgInvalidProperty: msgInvalidProperty,
msgInvalidPropertyName: msgInvalidPropertyName,
msgPropertyValueMustBeObject: msgPropertyValueMustBeObject,
msgPropertyRequiredWhen: msgPropertyRequiredWhen,
msgPropertyUnwantedWhen: msgPropertyUnwantedWhen,
msgValueCannotBeNull: msgValueCannotBeNull,
msgNull: msgNull,
msgValueMustBeObject: msgValueMustBeObject,
msgValueMustBeArray: msgValueMustBeArray,
msgValueMustBeObjectOrArray: msgValueMustBeObjectOrArray,
msgPropertyObjectValidatorError: msgPropertyObjectValidatorError,
msgNotEmpty: msgNotEmpty,
msgNotEmptyString: msgNotEmptyString,
msgNotBlankString: msgNotBlankString,
msgNoControlChars: msgNoControlChars,
msgValidPattern: msgValidPattern,
msgInvalidCharacters: msgInvalidCharacters,
msgStringValidJson: msgStringValidJson,
msgStringLowercase: msgStringLowercase,
msgStringUppercase: msgStringUppercase,
msgUnicodeNormalization: msgUnicodeNormalization,
msgUnicodeNormalizationNFC: msgUnicodeNormalizationNFC,
msgUnicodeNormalizationNFKC: msgUnicodeNormalizationNFKC,
msgUnicodeNormalizationNFD: msgUnicodeNormalizationNFD,
msgUnicodeNormalizationNFKD: msgUnicodeNormalizationNFKD,
msgPositive: msgPositive,
msgPositiveOrZero: msgPositiveOrZero,
msgNegative: msgNegative,
msgNegativeOrZero: msgNegativeOrZero,
msgArrayUnique: msgArrayUnique,
msgValidUuid: msgValidUuid,
msgValidCardNumber: msgValidCardNumber,
msgValidCountryCode: msgValidCountryCode,
msgValidCurrencyCode: msgValidCurrencyCode,
msgValidEmail: msgValidEmail,
msgValidLanguageCode: msgValidLanguageCode,
msgFailure: msgFailure,
msgValidISODate: msgValidISODate,
msgValidISODatetimeFormatFull: msgValidISODatetimeFormatFull,
msgValidISODatetimeFormatNoOffs: msgValidISODatetimeFormatNoOffs,
msgValidISODatetimeFormatNoMillis: msgValidISODatetimeFormatNoMillis,
msgValidISODatetimeFormatMin: msgValidISODatetimeFormatMin,
msgValidISODuration: msgValidISODuration,
msgValidTimezone: msgValidTimezone,
msgDatetimeDayOfWeek: msgDatetimeDayOfWeek,
msgDatetimeFuture: msgDatetimeFuture,
msgDatetimeFutureOrPresent: msgDatetimeFutureOrPresent,
msgDatetimePast: msgDatetimePast,
msgDatetimePastOrPresent: msgDatetimePastOrPresent,
msgPresetISBN: msgPresetISBN,
msgPresetISBN10: msgPresetISBN10,
msgPresetISBN13: msgPresetISBN13,
msgPresetISSN: msgPresetISSN,
msgPresetEAN: msgPresetEAN,
msgPresetEAN8: msgPresetEAN8,
msgPresetEAN13: msgPresetEAN13,
msgPresetDUN14: msgPresetDUN14,
msgPresetEAN14: msgPresetEAN14,
msgPresetEAN18: msgPresetEAN18,
msgPresetEAN99: msgPresetEAN99,
msgPresetUPC: msgPresetUPC,
msgPresetUPCA: msgPresetUPCA,
msgPresetUPCE: msgPresetUPCE,
msgPresetPublication: msgPresetPublication,
msgPresetAlpha: msgPresetAlpha,
msgPresetAlphaNumeric: msgPresetAlphaNumeric,
msgPresetBarcode: msgPresetBarcode,
msgPresetNumeric: msgPresetNumeric,
msgPresetInteger: msgPresetInteger,
msgPresetHexadecimal: msgPresetHexadecimal,
msgPresetCMYK: msgPresetCMYK,
msgPresetCMYK300: msgPresetCMYK300,
msgPresetHtmlColor: msgPresetHtmlColor,
msgPresetRgb: msgPresetRgb,
msgPresetRgba: msgPresetRgba,
msgPresetRgbIcc: msgPresetRgbIcc,
msgPresetHsl: msgPresetHsl,
msgPresetHsla: msgPresetHsla,
msgPresetE164: msgPresetE164,
msgPresetBase64: msgPresetBase64,
msgPresetBase64URL: msgPresetBase64URL,
msgPresetUuid1: msgPresetUuid1,
msgPresetUuid2: msgPresetUuid2,
msgPresetUuid3: msgPresetUuid3,
msgPresetUuid4: msgPresetUuid4,
msgPresetUuid5: msgPresetUuid5,
msgPresetULID: msgPresetULID,
msgValidMAC: msgValidMAC,
msgValidCIDR: msgValidCIDR,
msgValidCIDRv4: msgValidCIDRv4,
msgValidCIDRv6: msgValidCIDRv6,
msgValidHostname: msgValidHostname,
msgValidIP: msgValidIP,
msgValidIPv4: msgValidIPv4,
msgValidIPv6: msgValidIPv6,
msgValidTCP: msgValidTCP,
msgValidTCPv4: msgValidTCPv4,
msgValidTCPv6: msgValidTCPv6,
msgValidUDP: msgValidUDP,
msgValidUDPv4: msgValidUDPv4,
msgValidUDPv6: msgValidUDPv6,
msgValidTld: msgValidTld,
msgValidURI: msgValidURI,
msgValidURL: msgValidURL,
msgQueryParamMultiNotAllowed: msgQueryParamMultiNotAllowed,
}
// used by defaultI18nContext.MarshalJSON - to allow listing of translation reference
// also as a kind of double-entry bookkeeping to ensure everything has been translated into TranslationsFormats
var internalFormats = map[string]string{
// property validator...
fmtMsgValueExpectedType: fmtMsgValueExpectedType,
// constraints...
fmtMsgUnknownPresetPattern: fmtMsgUnknownPresetPattern,
fmtMsgValidToken: fmtMsgValidToken,
fmtMsgStringMinLen: fmtMsgStringMinLen,
fmtMsgStringMinLenExc: fmtMsgStringMinLenExc,
fmtMsgStringMaxLen: fmtMsgStringMaxLen,
fmtMsgStringMaxLenExc: fmtMsgStringMaxLenExc,
fmtMsgStringExactLen: fmtMsgStringExactLen,
fmtMsgStringMinMaxLen: fmtMsgStringMinMaxLen,
fmtMsgMinLen: fmtMsgMinLen,
fmtMsgMinLenExc: fmtMsgMinLenExc,
fmtMsgExactLen: fmtMsgExactLen,
fmtMsgMinMax: fmtMsgMinMax,
fmtMsgGt: fmtMsgGt,
fmtMsgGte: fmtMsgGte,
fmtMsgLt: fmtMsgLt,
fmtMsgLte: fmtMsgLte,
fmtMsgStrGt: fmtMsgStrGt,
fmtMsgStrGte: fmtMsgStrGte,
fmtMsgStrLt: fmtMsgStrLt,
fmtMsgStrLte: fmtMsgStrLte,
fmtMsgRange: fmtMsgRange,
fmtMsgMultipleOf: fmtMsgMultipleOf,
fmtMsgArrayElementType: fmtMsgArrayElementType,
fmtMsgArrayElementTypeOrNull: fmtMsgArrayElementTypeOrNull,
fmtMsgUuidMinVersion: fmtMsgUuidMinVersion,
fmtMsgUuidCorrectVer: fmtMsgUuidCorrectVer,
fmtMsgEqualsOther: fmtMsgEqualsOther,
fmtMsgNotEqualsOther: fmtMsgNotEqualsOther,
fmtMsgGtOther: fmtMsgGtOther,
fmtMsgGteOther: fmtMsgGteOther,
fmtMsgLtOther: fmtMsgLtOther,
fmtMsgLteOther: fmtMsgLteOther,
fmtMsgDtGt: fmtMsgDtGt,
fmtMsgDtGte: fmtMsgDtGte,
fmtMsgDtLt: fmtMsgDtLt,
fmtMsgDtLte: fmtMsgDtLte,
fmtMsgStringContains: fmtMsgStringContains,
fmtMsgStringNotContains: fmtMsgStringNotContains,
fmtMsgStringStartsWith: fmtMsgStringStartsWith,
fmtMsgStringNotStartsWith: fmtMsgStringNotStartsWith,
fmtMsgStringEndsWith: fmtMsgStringEndsWith,
fmtMsgStringNotEndsWith: fmtMsgStringNotEndsWith,
// datetime tolerances...
fmtMsgDtToleranceFixedSame: fmtMsgDtToleranceFixedSame,
fmtMsgDtToleranceFixedMaxAfter: fmtMsgDtToleranceFixedMaxAfter,
fmtMsgDtToleranceFixedMaxBefore: fmtMsgDtToleranceFixedMaxBefore,
fmtMsgDtToleranceFixedMinAfter: fmtMsgDtToleranceFixedMinAfter,
fmtMsgDtToleranceFixedMinBefore: fmtMsgDtToleranceFixedMinBefore,
fmtMsgDtToleranceNowSame: fmtMsgDtToleranceNowSame,
fmtMsgDtToleranceNowMaxAfter: fmtMsgDtToleranceNowMaxAfter,
fmtMsgDtToleranceNowMaxBefore: fmtMsgDtToleranceNowMaxBefore,
fmtMsgDtToleranceNowMinAfter: fmtMsgDtToleranceNowMinAfter,
fmtMsgDtToleranceNowMinBefore: fmtMsgDtToleranceNowMinBefore,
fmtMsgDtToleranceOtherSame: fmtMsgDtToleranceOtherSame,
fmtMsgDtToleranceOtherMaxAfter: fmtMsgDtToleranceOtherMaxAfter,
fmtMsgDtToleranceOtherMaxBefore: fmtMsgDtToleranceOtherMaxBefore,
fmtMsgDtToleranceOtherMinAfter: fmtMsgDtToleranceOtherMinAfter,
fmtMsgDtToleranceOtherMinBefore: fmtMsgDtToleranceOtherMinBefore,
// datetime age...
fmtMsgDtAgeMin: fmtMsgDtAgeMin,
fmtMsgDtAgeMinOrOver: fmtMsgDtAgeMinOrOver,
fmtMsgDtAgeMax: fmtMsgDtAgeMax,
fmtMsgDtAgeMaxOrUnder: fmtMsgDtAgeMaxOrUnder,
fmtMsgDtAgeMinExcMaxExc: fmtMsgDtAgeMinExcMaxExc,
fmtMsgDtAgeMinMax: fmtMsgDtAgeMinMax,
fmtMsgDtAgeMinMaxExc: fmtMsgDtAgeMinMaxExc,
fmtMsgDtAgeMinExcMax: fmtMsgDtAgeMinExcMax,
// constraint set...
fmtMsgConstraintSetDefaultAllOf: fmtMsgConstraintSetDefaultAllOf,
fmtMsgConstraintSetDefaultOneOf: fmtMsgConstraintSetDefaultOneOf,
// request query validate...
fmtMsgQueryParamType: fmtMsgQueryParamType,
}
// used by defaultI18nContext.MarshalJSON - to allow listing of translation reference
// also as a kind of double-entry bookkeeping to ensure everything has been translated into TranslationsTokens
// "..." at the end indicates pluralisation
var internalTokens = map[string]string{
jsonTypeTokenString: jsonTypeTokenString,
jsonTypeTokenNumber: jsonTypeTokenNumber,
jsonTypeTokenInteger: jsonTypeTokenInteger,
jsonTypeTokenBoolean: jsonTypeTokenBoolean,
jsonTypeTokenObject: jsonTypeTokenObject,
jsonTypeTokenArray: jsonTypeTokenArray,
jsonTypeTokenAny: jsonTypeTokenAny,
tokenInclusive: tokenInclusive,
tokenExclusive: tokenExclusive,
"millennium": "millennium",
"millennium...": "millennia",
"century": "century",
"century...": "centuries",
"decade": "decade",
"decade...": "decades",
"year": "year",
"year...": "years",
"month": "month",
"month...": "months",
"week": "week",
"week...": "weeks",
"day": "day",
"day...": "days",
"hour": "hour",
"hour...": "hours",
"minute": "minute",
"minute...": "minutes",
"second": "second",
"second...": "seconds",
"millisecond": "millisecond",
"millisecond...": "milliseconds",
"microsecond": "microsecond",
"microsecond...": "microseconds",
"nanosecond": "nanosecond",
"nanosecond...": "nanoseconds",
}