-
Notifications
You must be signed in to change notification settings - Fork 37
/
i18n.go
136 lines (117 loc) · 2.59 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
package air
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
"github.com/pelletier/go-toml"
"golang.org/x/text/language"
)
// i18n is a locale manager that adapts to the request's favorite conventions.
type i18n struct {
a *Air
loadOnce *sync.Once
loadError error
watcher *fsnotify.Watcher
matcher language.Matcher
locales map[string]map[string]string
}
// newI18n returns a new instance of the `i18n` with the a.
func newI18n(a *Air) *i18n {
return &i18n{
a: a,
loadOnce: &sync.Once{},
}
}
// load loads the stuff of the i up.
func (i *i18n) load() {
defer func() {
if i.loadError != nil {
i.loadOnce = &sync.Once{}
}
}()
if i.watcher == nil {
i.watcher, i.loadError = fsnotify.NewWatcher()
if i.loadError != nil {
return
}
go func() {
for {
select {
case <-i.watcher.Events:
i.loadOnce = &sync.Once{}
case err := <-i.watcher.Errors:
i.a.logErrorf(
"air: i18n watcher error: %v",
err,
)
case <-i.a.context.Done():
return
}
}
}()
}
var lr string
lr, i.loadError = filepath.Abs(i.a.I18nLocaleRoot)
if i.loadError != nil {
return
}
var fis []os.FileInfo
if fis, i.loadError = ioutil.ReadDir(lr); i.loadError != nil {
return
}
ts := make([]language.Tag, 0, len(fis))
ls := make(map[string]map[string]string, len(ts))
for _, fi := range fis {
if fi.IsDir() {
continue
}
var t language.Tag
if ext := filepath.Ext(fi.Name()); strings.ToLower(
ext,
) != ".toml" {
continue
} else if t, i.loadError = language.Parse(strings.TrimSuffix(
fi.Name(),
ext,
)); i.loadError != nil {
return
}
n := filepath.Join(lr, fi.Name())
l := map[string]string{}
var tt *toml.Tree
if tt, i.loadError = toml.LoadFile(n); i.loadError != nil {
return
} else if i.loadError = tt.Unmarshal(&l); i.loadError != nil {
return
} else if i.loadError = i.watcher.Add(n); i.loadError != nil {
return
}
ts = append(ts, t)
ls[t.String()] = l
}
i.matcher = language.NewMatcher(ts)
i.locales = ls
}
// localize localizes the r.
func (i *i18n) localize(r *Request) {
if i.loadOnce.Do(i.load); i.loadError != nil {
i.a.logErrorf("air: failed to load i18n: %v", i.loadError)
r.localizedString = locstr
return
}
t, _ := language.MatchStrings(i.matcher, r.Header["Accept-Language"]...)
l := i.locales[t.String()]
r.localizedString = func(key string) string {
if v, ok := l[key]; ok {
return v
} else if l, ok := i.locales[i.a.I18nLocaleBase]; ok {
if v, ok := l[key]; ok {
return v
}
}
return key
}
}