-
Notifications
You must be signed in to change notification settings - Fork 11
/
language.go
206 lines (188 loc) · 4.36 KB
/
language.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
/*
Copyright 2016 Wenhui Shen <www.webx.top>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package language
import (
"bytes"
"regexp"
"strings"
"sync"
"github.com/webx-top/com"
"github.com/webx-top/echo"
"github.com/webx-top/echo/engine"
)
var (
LangVarName = `lang`
DefaultLang = `zh-cn`
headerAcceptRemove = regexp.MustCompile(`;q=[0-9.]+`)
)
func New(c ...*Config) *Language {
lang := &Language{
List: make(map[string]bool),
Index: make([]string, 0),
Default: DefaultLang,
translatePool: sync.Pool{
New: func() interface{} {
return &Translate{}
},
},
}
if len(c) > 0 {
lang.Init(c[0])
}
return lang
}
type Language struct {
List map[string]bool //语种列表
Index []string //索引
Default string //默认语种
I18n *I18n
translatePool sync.Pool
}
func (a *Language) Init(c *Config) {
if c.AllList != nil {
for _, lang := range c.AllList {
a.Set(lang, true, lang == c.Default)
}
} else {
a.Set(c.Default, true, true)
if c.Default != `en` {
a.Set(`en`, true)
}
}
a.I18n = NewI18n(c)
if c.Reload {
a.I18n.Monitor()
}
}
func (a *Language) Set(lang string, on bool, args ...bool) *Language {
if a.List == nil {
a.List = make(map[string]bool)
}
if _, ok := a.List[lang]; !ok {
a.Index = append(a.Index, lang)
}
a.List[lang] = on
if on && len(args) > 0 && args[0] {
a.Default = lang
}
return a
}
func (a *Language) DetectURI(r engine.Request) string {
p := strings.TrimPrefix(r.URL().Path(), `/`)
s := strings.Index(p, `/`)
var lang string
if s != -1 {
lang = p[0:s]
} else {
lang = p
}
if len(lang) == 0 {
return lang
}
on, ok := a.List[lang]
if !ok {
return ``
}
r.URL().SetPath(strings.TrimPrefix(p, lang))
if !on {
return ``
}
return lang
}
func (a *Language) Valid(lang string) bool {
if len(lang) == 0 {
return false
}
if on, ok := a.List[lang]; ok {
return on
}
return false
}
func ParseHeader(al string, n int) []string {
if len(al) == 0 {
return []string{}
}
al = headerAcceptRemove.ReplaceAllString(al, ``)
return strings.SplitN(al, `,`, n)
}
func (a *Language) DetectHeader(r engine.Request) string {
lg := ParseHeader(r.Header().Get(`Accept-Language`), 5)
for _, lang := range lg {
lang = strings.ToLower(lang)
if a.Valid(lang) {
return lang
}
lang = strings.SplitN(lang, `-`, 2)[0]
if a.Valid(lang) {
return lang
}
}
return a.Default
}
func (a *Language) Middleware() echo.MiddlewareFunc {
return echo.MiddlewareFunc(func(h echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error {
lang := c.Query(LangVarName)
var hasCookie bool
if !a.Valid(lang) {
lang = a.DetectURI(c.Request())
if !a.Valid(lang) {
lang = c.GetCookie(LangVarName)
if !a.Valid(lang) {
lang = a.DetectHeader(c.Request())
} else {
hasCookie = true
}
}
}
if !hasCookie {
c.SetCookie(LangVarName, lang)
}
tr := a.translatePool.Get().(*Translate)
tr.Reset(lang, a.I18n)
defer a.translatePool.Put(tr)
c.SetTranslator(tr)
return h.Handle(c)
})
})
}
func (a *Language) Handler(e echo.RouteRegister, i18nJSVarName string) {
e.Get(`/i18n.json`, func(c echo.Context) error {
t := a.I18n.Get(c.Lang().String())
if t != nil {
messages := t.Messages()
return c.JSON(messages)
}
return c.JSONBlob([]byte(`{}`))
})
e.Get(`/i18n.js`, func(c echo.Context) error {
t := a.I18n.Get(c.Lang().String())
buf := bytes.NewBuffer(nil)
if t != nil {
messages := t.Messages()
if messages != nil {
if len(i18nJSVarName) > 0 {
buf.WriteString(i18nJSVarName + `=`)
}
b, _ := com.JSONEncode(messages)
if len(b) > 0 {
buf.Write(b)
} else {
buf.WriteString(`{}`)
}
}
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextJavaScriptCharsetUTF8)
return c.Blob(buf.Bytes())
})
}