-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.go
119 lines (101 loc) · 2.28 KB
/
plugin.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
111
112
113
114
115
116
117
118
119
package TreblleTraefikPluginGo
import (
"context"
"net/http"
"net/http/httptest"
"regexp"
"time"
)
type Config struct {
ApiKey string
ProjectId string
AdditionalFieldsToMask []string
RoutesToBlock []string
RoutesRegex string
DebugMode bool
}
func CreateConfig() *Config {
return &Config{}
}
type Treblle struct {
next http.Handler
name string
ApiKey string
ProjectId string
FieldsMap map[string]bool
RoutesToBlock []string
RoutesRegex *regexp.Regexp
serverInfo ServerInfo
languageInfo LanguageInfo
DebugMode bool
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
t := &Treblle{
next: next,
name: name,
}
if config.ApiKey != "" {
t.ApiKey = config.ApiKey
}
if config.ProjectId != "" {
t.ProjectId = config.ProjectId
}
if len(config.AdditionalFieldsToMask) > 0 {
t.FieldsMap = generateFieldsToMask(config.AdditionalFieldsToMask)
}
if len(config.RoutesToBlock) > 0 {
t.RoutesToBlock = config.RoutesToBlock
}
if config.DebugMode {
t.DebugMode = true
}
if config.RoutesRegex != "" {
re, err := regexp.Compile(config.RoutesRegex)
if err != nil {
return nil, err
}
t.RoutesRegex = re
}
t.serverInfo = getServerInfo()
t.languageInfo = getLanguageInfo()
return t, nil
}
func (t *Treblle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if len(t.RoutesToBlock) > 0 {
for _, route := range t.RoutesToBlock {
if r.RequestURI == route {
t.next.ServeHTTP(w, r)
return
}
}
}
if t.RoutesRegex != nil {
if t.RoutesRegex.MatchString(r.RequestURI) {
t.next.ServeHTTP(w, r)
return
}
}
startTime := time.Now()
reqInfo, _ := t.getRequestInfo(r, startTime)
rec := httptest.NewRecorder()
t.next.ServeHTTP(rec, r)
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, _ = w.Write(rec.Body.Bytes())
ti := Metadata{
ApiKey: t.ApiKey,
ProjectID: t.ProjectId,
Version: "1.0.5",
Sdk: "traefik-go",
Data: DataInfo{
Server: t.serverInfo,
Language: t.languageInfo,
Request: reqInfo,
Response: t.getResponseInfo(rec, startTime),
},
}
// don't block execution while sending data to Treblle
go t.sendToTreblle(ti)
}