-
Notifications
You must be signed in to change notification settings - Fork 55
/
middleware.go
147 lines (127 loc) · 3.54 KB
/
middleware.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package bramble
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime"
"net"
"net/http"
"strings"
"github.com/felixge/httpsnoop"
"github.com/prometheus/client_golang/prometheus"
)
type middleware func(http.Handler) http.Handler
// DebugKey is used to request debug info from the context
const DebugKey contextKey = "debug"
const (
debugHeader = "X-Bramble-Debug"
)
// DebugInfo contains the requested debug info for a query
type DebugInfo struct {
Variables bool
Query bool
Plan bool
Timing bool
TraceID bool
}
func debugMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
info := DebugInfo{}
for _, field := range strings.Fields(r.Header.Get(debugHeader)) {
switch field {
case "all":
info.Variables = true
info.Plan = true
info.Query = true
info.Timing = true
info.TraceID = true
case "query":
info.Query = true
case "variables":
info.Variables = true
case "plan":
info.Plan = true
case "timing":
info.Timing = true
case "traceid":
info.TraceID = true
}
}
ctx := context.WithValue(r.Context(), DebugKey, info)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
func monitoringMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, event := startEvent(r.Context(), nameMonitoringEvent)
if !strings.HasPrefix(r.Header.Get("user-agent"), "Bramble") {
defer event.finish()
}
if host := r.Header.Get("X-Forwarded-Host"); host != "" {
event.addField("forwarded_host", host)
}
var buf bytes.Buffer
_, err := io.Copy(&buf, r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
r.Body = io.NopCloser(&buf)
r = r.WithContext(ctx)
addRequestBody(event, r, buf)
m := httpsnoop.CaptureMetrics(h, w, r)
event.addFields(EventFields{
"response.status": m.Code,
"request.path": r.URL.Path,
"response.size": m.Written,
})
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
event.addField("request.ip", ip)
}
promHTTPRequestCounter.With(prometheus.Labels{
"code": fmt.Sprintf("%dXX", m.Code/100),
}).Inc()
promHTTPRequestSizes.With(prometheus.Labels{}).Observe(float64(buf.Len()))
promHTTPResponseSizes.With(prometheus.Labels{}).Observe(float64(m.Written))
promHTTPResponseDurations.With(prometheus.Labels{}).Observe(m.Duration.Seconds())
})
}
func nameMonitoringEvent(fields EventFields) string {
if t := fields["operation.type"]; t != nil {
if n := fields["operation.name"]; n != "" {
return fmt.Sprintf("%s:%s", t, n)
}
return fmt.Sprintf("%s", t)
}
return "request"
}
func addRequestBody(e *event, r *http.Request, buf bytes.Buffer) {
contentType, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
e.addField("request.content-type", contentType)
if r.Method != http.MethodHead && r.Method != http.MethodGet {
switch {
case contentType == "application/json":
var payload interface{}
if err := json.Unmarshal(buf.Bytes(), &payload); err == nil {
e.addField("request.body", &payload)
} else {
e.addField("request.body", buf.String())
e.addField("request.error", err)
}
case contentType == "multipart/form-data":
e.addField("request.body", fmt.Sprintf("%d bytes", len(buf.Bytes())))
default:
e.addField("request.body", buf.String())
}
} else {
e.addField("request.body", buf.String())
}
}
func applyMiddleware(h http.Handler, mws ...middleware) http.Handler {
for _, mw := range mws {
h = mw(h)
}
return h
}