-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client.go
86 lines (67 loc) · 1.78 KB
/
http_client.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
package xecho
import (
"github.com/newrelic/go-agent"
"net/http"
"net/http/httputil"
"time"
)
type loggingTransport struct {
inboundContext *Context
isDebug bool
transport http.RoundTripper
}
// Wraps the outbound request round trip with logging and metrics
func (t *loggingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
segment := newrelic.StartExternalSegment(t.inboundContext.NewRelicTx, r)
logger := t.inboundContext.Logger().(*Logger)
if err := debugDumpRequest(r, logger, t.isDebug); err != nil {
return nil, err
}
startTime := time.Now()
res, err := t.transport.RoundTrip(r)
segment.Response = res
_ = segment.End()
if err != nil {
logger.Errorf("Failed to get response in outbound request: %s %s", r.Method, r.URL.String())
return nil, err
}
reqTime := time.Now().Sub(startTime)
logger.Infof("Outgoing request: %s %s %d (%fs)", r.Method, r.URL.String(), res.StatusCode, reqTime.Seconds())
if err := debugDumpResponse(res, logger, t.isDebug); err != nil {
return nil, err
}
return res, nil
}
func NewHttpClient(
context *Context,
isDebug bool,
) *http.Client {
loggingTransport := &loggingTransport{
inboundContext: context,
isDebug: isDebug,
transport: &http.Transport{},
}
return &http.Client{Transport: loggingTransport}
}
func debugDumpRequest(r *http.Request, logger *Logger, isDebug bool) error {
if !isDebug {
return nil
}
reqDump, err := httputil.DumpRequest(r, true)
if err != nil {
return err
}
logger.Debugf("%s", string(reqDump))
return nil
}
func debugDumpResponse(res *http.Response, logger *Logger, isDebug bool) error {
if !isDebug {
return nil
}
resDump, err := httputil.DumpResponse(res, true)
if err != nil {
return err
}
logger.Debugf("%s", string(resDump))
return nil
}