/
setup.go
97 lines (82 loc) · 2.06 KB
/
setup.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
package locale
import (
"strings"
"github.com/caddyserver/caddy"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
"github.com/simia-tech/caddy-locale/method"
)
func init() {
caddy.RegisterPlugin("locale", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
func setup(c *caddy.Controller) error {
l, err := parseLocale(c)
if err != nil {
return err
}
siteConfig := httpserver.GetConfig(c)
siteConfig.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
l.Next = next
return l
})
return nil
}
func parseLocale(c *caddy.Controller) (*Middleware, error) {
result := &Middleware{
AvailableLocales: []string{},
Methods: []method.Method{},
PathScope: "/",
Configuration: &method.Configuration{
CookieName: "locale",
},
}
for c.Next() {
args := c.RemainingArgs()
if len(args) > 0 {
result.AvailableLocales = append(result.AvailableLocales, args...)
}
for c.NextBlock() {
switch c.Val() {
case "available":
result.AvailableLocales = append(result.AvailableLocales, c.RemainingArgs()...)
case "detect":
detectArgs := c.RemainingArgs()
if len(detectArgs) == 0 {
return nil, c.ArgErr()
}
for _, detectArg := range detectArgs {
method, found := method.Names[strings.ToLower(strings.TrimSpace(detectArg))]
if !found {
return nil, c.Errf("could not find detect method [%s]", detectArg)
}
result.Methods = append(result.Methods, method)
}
case "cookie":
if !c.NextArg() {
return nil, c.ArgErr()
}
if value := strings.TrimSpace(c.Val()); value != "" {
result.Configuration.CookieName = value
}
case "path":
if !c.NextArg() {
return nil, c.ArgErr()
}
if value := strings.TrimSpace(c.Val()); value != "" {
result.PathScope = value
}
default:
return nil, c.ArgErr()
}
}
}
if len(result.AvailableLocales) == 0 {
return nil, c.Errf("no available locales specified")
}
if len(result.Methods) == 0 {
result.Methods = append(result.Methods, method.Names["header"])
}
return result, nil
}