/
setup.go
92 lines (84 loc) · 1.63 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
package static
import (
super "github.com/caibirdme/durian/server"
"github.com/mholt/caddy"
"github.com/valyala/fasthttp"
"strings"
)
func init() {
caddy.RegisterPlugin(super.DirectiveStatic, caddy.Plugin{
ServerType: super.FastHTTPServerType,
Action: setup,
})
}
var (
rootPath = []byte("/")
)
func setup(c *caddy.Controller) error {
cfg := StaticConfig{}
err := parseStatic(c, &cfg)
if err != nil {
return err
}
srvCfg := super.GetConfig(c)
if cfg.Root == "" {
cfg.Root = srvCfg.Root
}
fs := &fasthttp.FS{
Root: cfg.Root,
Compress: cfg.Compress,
IndexNames: cfg.Index,
}
process := fs.NewRequestHandler()
srvCfg.AddMiddleware(func(next fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
if !cfg.location.Match(ctx.Path()) {
next(ctx)
} else {
process(ctx)
}
}
})
return nil
}
type StaticConfig struct {
location super.LocationMatcher
Root string
Index []string
Compress bool
}
func parseStatic(c *caddy.Controller, cfg *StaticConfig) error {
// skip root
c.Next()
location, err := super.NewLocationMatcher(c.RemainingArgs())
if err != nil {
return c.Err(err.Error())
}
cfg.location = location
hasBlock := false
for c.NextBlock() {
hasBlock = true
kind := c.Val()
switch strings.ToLower(kind) {
case "root":
if !c.NextArg() {
return c.ArgErr()
}
cfg.Root = c.Val()
case "compress":
cfg.Compress = true
case "index":
for c.NextArg() {
cfg.Index = append(cfg.Index, c.Val())
}
}
}
if !hasBlock {
// root dir
if !c.NextArg() {
return c.ArgErr()
}
cfg.Root = c.Val()
}
return nil
}