caddy自定义插件

安装caddy和xcaddy

1
2
下载caddy_2.8.4_linux_amd64.deb xcaddy_0.4.2_linux_amd64.deb 
dpkg -i 安装

初始化go项目

1
2
3
4
5
6
7
8
go mod init mymodule
root@v:~/mymodule# tree
.
├── caddy
├── Caddyfile
├── go.mod
├── go.sum
└── mymodule.go

mymodule.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
package mymodule

import (
"errors"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"net/http"
)

func init() {
caddy.RegisterModule(&HelloWorld{})
httpcaddyfile.RegisterHandlerDirective("hello_world", parseCaddyfile)
}

type HelloWorld struct {
Text string `json:"text,omitempty"`
}

func (h *HelloWorld) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
for d.Next() {
if !d.Args(&h.Text) {
// not enough args
return d.ArgErr()
}
if d.NextArg() {
// too many args
return d.ArgErr()
}
}
return nil
}
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
hw := new(HelloWorld)
err := hw.UnmarshalCaddyfile(h.Dispenser)
return hw, err
}
func (h *HelloWorld) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
err := next.ServeHTTP(w, r)
if err != nil {
return err
}
w.Write([]byte(h.Text))
return nil
}
func (h HelloWorld) Validate() error {
if h.Text == "" {
return errors.New("the text is must!!!")
}
return nil
}
func (h *HelloWorld) Provision(ctx caddy.Context) error {
//h.Text = "Hello 世界"
return nil
}

// CaddyModule returns the Caddy module information.
func (h HelloWorld) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.hello_world",
New: func() caddy.Module { return new(HelloWorld) },
}
}

var (
_ caddy.Provisioner = (*HelloWorld)(nil)
_ caddy.Validator = (*HelloWorld)(nil)
_ caddyhttp.MiddlewareHandler = (*HelloWorld)(nil)
_ caddyfile.Unmarshaler = (*HelloWorld)(nil)
)

Caddyfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  order hello_world last
debug
}
:80 {
  hello_world 打印内容
}


# 或者
{
order hello_world last
}
:80 {

reverse_proxy "127.0.0.1:8080" {
handle_response {
hello_world "test"
}
}

}

查看插件

1
xcaddy list-modules

直接跑

1
xcaddy run --config Caddyfile

打包

1
2
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 xcaddy build --with mymodule=.   # .表示当前目录
./caddy run --config Caddyfile