-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.go
63 lines (52 loc) · 1.45 KB
/
middleware.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
package locale
import (
"net/http"
"strings"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
"github.com/simia-tech/caddy-locale/method"
)
// Middleware is a httpserver to detect the user's locale.
type Middleware struct {
Next httpserver.Handler
AvailableLocales []string
Methods []method.Method
PathScope string
Configuration *method.Configuration
}
// ServeHTTP implements the httpserver.Handler interface.
func (l *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
if !httpserver.Path(r.URL.Path).Matches(l.PathScope) {
return l.Next.ServeHTTP(w, r)
}
candidates := []string{}
for _, method := range l.Methods {
candidates = append(candidates, method(r, l.Configuration)...)
}
locale := l.firstValid(candidates)
if locale == "" {
locale = l.defaultLocale()
}
r.Header.Set("Detected-Locale", locale)
return l.Next.ServeHTTP(w, r)
}
func (l *Middleware) defaultLocale() string {
return l.AvailableLocales[0]
}
func (l *Middleware) firstValid(candidates []string) string {
for _, candidate := range candidates {
candidate = strings.TrimSpace(candidate)
if val := l.validAvailableLocale(candidate); val != "" {
return val
}
}
return ""
}
func (l *Middleware) validAvailableLocale(locale string) string {
locale = strings.ToLower(locale)
for _, validLocale := range l.AvailableLocales {
if locale == strings.ToLower(validLocale) {
return validLocale
}
}
return ""
}