-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
42 lines (31 loc) · 871 Bytes
/
context.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
package i18n
import (
"context"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
type i18nCtxType uint8
const (
langCtxKey i18nCtxType = iota
printerCtxKey
)
func ContextWithLang(ctx context.Context, lang language.Tag) context.Context {
ctx = context.WithValue(ctx, langCtxKey, lang)
ctx = context.WithValue(ctx, printerCtxKey, GetPrinter(lang))
return ctx
}
func PrinterFromContext(ctx context.Context) *message.Printer {
if p, ok := ctx.Value(printerCtxKey).(*message.Printer); ok {
return p
}
return GetPrinter(LanguageFromContext(ctx))
}
func Sprintf(ctx context.Context, val string, args ...interface{}) string {
return PrinterFromContext(ctx).Sprintf(val, args...)
}
func LanguageFromContext(ctx context.Context) language.Tag {
if lang, ok := ctx.Value(langCtxKey).(language.Tag); ok {
return lang
}
return defaultLanguage
}