-
Notifications
You must be signed in to change notification settings - Fork 20
/
caddyfile.go
81 lines (68 loc) · 1.73 KB
/
caddyfile.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
package dynamichandler
import (
"fmt"
"path/filepath"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func init() {
httpcaddyfile.RegisterHandlerDirective("dynamic_handler", parseCaddyfile)
}
// parseCaddyfile sets up a handler from Caddyfile tokens.
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
dh := new(DynamicHandler)
if err := dh.UnmarshalCaddyfile(h.Dispenser); err != nil {
return nil, err
}
return dh, nil
}
// UnmarshalCaddyfile implements caddyfile.Unmarshaler. Syntax:
//
// dynamic_handler <name> {
// root <root>
// config <config>
// }
//
func (dh *DynamicHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if !d.Next() {
return d.ArgErr()
}
if !d.NextArg() {
return d.ArgErr()
}
dh.Name = d.Val()
// Get the path of the Caddyfile.
caddyfilePath, err := filepath.Abs(d.File())
if err != nil {
return fmt.Errorf("failed to get absolute path of file: %s: %v", d.File(), err)
}
caddyfileDir := filepath.Dir(caddyfilePath)
dh.Root = caddyfileDir // Defaults to the directory of the Caddyfile.
for nesting := d.Nesting(); d.NextBlock(nesting); {
switch d.Val() {
case "root":
if !d.NextArg() {
return d.ArgErr()
}
root := d.Val()
if filepath.IsAbs(root) {
dh.Root = root
return nil
}
// Make the path relative to the Caddyfile rather than the
// current working directory.
dh.Root = filepath.Join(caddyfileDir, root)
case "config":
if !d.NextArg() {
return d.ArgErr()
}
dh.Config = d.Val()
}
}
return nil
}
// Interface guards
var (
_ caddyfile.Unmarshaler = (*DynamicHandler)(nil)
)