generated from traefik/plugindemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (88 loc) · 2.03 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
// Package plugindemo a demo plugin.
package statusdonrouters
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httputil"
)
// Config the plugin configuration.
type Config struct {
Ip string `json:"ip"`
Port string `json:"port"`
ServerPrefix string `json:"serverPrefix"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
// Demo a Demo plugin.
type Plugin struct {
next http.Handler
name string
config *Config
}
// New created a new Demo plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
return &Plugin{
next: next,
name: name,
config: config,
}, nil
}
type Metric struct {
Server string `json:"server"`
Host string `json:"host"`
Method string `json:"method"`
Path string `json:"path"`
RequestSize int `json:"requestSize"`
ResponseSize int `json:"responseSize"`
}
func (p *Plugin) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// create a custom response writer to intercept the response
crw := &customResponseWriter{ResponseWriter: rw}
m := &Metric{}
p.next.ServeHTTP(crw, req)
// dump the request and get its size
dump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
}
m.Server = p.config.ServerPrefix
m.Host = req.Host
m.Method = req.Method
m.Path = req.URL.Path
m.RequestSize = len(dump)
m.ResponseSize = crw.size
go p.send(m)
}
func (p *Plugin) send(metric *Metric) {
v, err := json.Marshal(metric)
if err != nil {
// TODO não sei o que fazer aqui
return
}
h := fmt.Sprint(
p.config.Ip,
":",
p.config.Port,
)
conn, err := net.Dial("udp", h)
if err != nil {
// TODO não sei o que fazer aqui
return
}
defer conn.Close()
fmt.Fprint(conn, string(v))
}
type customResponseWriter struct {
http.ResponseWriter
size int
}
func (crw *customResponseWriter) Write(b []byte) (int, error) {
n, err := crw.ResponseWriter.Write(b)
crw.size += n
return n, err
}