-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.go
67 lines (56 loc) · 1.42 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
package treblle
import (
"errors"
"log"
"net/http"
"net/http/httptest"
"time"
)
const (
treblleVersion = "0.7.2"
sdkName = "go"
)
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
requestInfo, errReqInfo := getRequestInfo(r, startTime)
// intercept the response so it can be copied
rec := httptest.NewRecorder()
// do the actual request as intended
next.ServeHTTP(rec, r)
// after this finishes, we have the response recorded
// copy the original headers
for k, v := range rec.Header() {
w.Header()[k] = v
}
// copy the original code
w.WriteHeader(rec.Code)
// write the original body
_, err := w.Write(rec.Body.Bytes())
if err != nil {
return
}
if !errors.Is(errReqInfo, ErrNotJson) {
ti := MetaData{
ApiKey: Config.APIKey,
ProjectID: Config.ProjectID,
Version: treblleVersion,
Sdk: sdkName,
Data: DataInfo{
Server: Config.serverInfo,
Language: Config.languageInfo,
Request: requestInfo,
Response: getResponseInfo(rec, startTime),
},
}
// don't block execution while sending data to Treblle
go sendToTreblle(ti)
}
})
}
// If anything happens to go wrong inside one of treblle-go internals, recover from panic and continue
func dontPanic() {
if err := recover(); err != nil {
log.Printf("treblle-go panic: %s", err)
}
}