-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
84 lines (70 loc) · 1.99 KB
/
module.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
package local_metrics_proxy
import (
"errors"
"fmt"
"io"
"net"
"net/http"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"go.uber.org/zap"
)
const (
// ModuleName is the name of the module.
ModuleName = "local_metrics_proxy"
// ModuleName is the namespace of the module.
ModuleNamespace = "http.handlers"
)
// Interface guards
var (
_ caddy.Provisioner = (*LocalMetricsProxy)(nil)
_ caddyhttp.MiddlewareHandler = (*LocalMetricsProxy)(nil)
_ caddyfile.Unmarshaler = (*LocalMetricsProxy)(nil)
)
func init() {
caddy.RegisterModule(LocalMetricsProxy{})
}
// UnixBackend is the unix-socket backend
type UnixBackend struct {
Path string `json:"path"`
}
// LocalMetricsProxy holds a configured instance of the proxy.
type LocalMetricsProxy struct {
UdsBackend *UnixBackend `json:"uds,omitempty"`
logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
func (LocalMetricsProxy) CaddyModule() caddy.ModuleInfo {
id := fmt.Sprintf("%s.%s", ModuleNamespace, ModuleName)
return caddy.ModuleInfo{
ID: caddy.ModuleID(id),
New: func() caddy.Module { return new(LocalMetricsProxy) },
}
}
// Provision sets up the module.
func (lmp *LocalMetricsProxy) Provision(ctx caddy.Context) error {
if lmp.UdsBackend == nil || lmp.UdsBackend.Path == "" {
return errors.New("proxy backend not configured")
}
lmp.logger = ctx.Logger(lmp)
return nil
}
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (lmp LocalMetricsProxy) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
if lmp.UdsBackend == nil || lmp.UdsBackend.Path == "" {
return errors.New("proxy backend not configured")
}
dialer := net.Dialer{}
conn, err := dialer.Dial("unix", lmp.UdsBackend.Path)
if err != nil {
return err
}
if _, err := io.Copy(w, conn); err != nil {
return err
}
if err := conn.Close(); err != nil {
return err
}
return next.ServeHTTP(w, r)
}