forked from xmidt-org/caduceus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpClient.go
72 lines (57 loc) · 1.51 KB
/
httpClient.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
// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"errors"
"net/http"
"strconv"
"time"
"github.com/go-kit/kit/metrics"
)
var (
errNilHistogram = errors.New("histogram cannot be nil")
)
type httpClient interface {
Do(*http.Request) (*http.Response, error)
}
func nopHTTPClient(next httpClient) httpClient {
return next
}
// DoerFunc implements HTTPClient
type doerFunc func(*http.Request) (*http.Response, error)
func (d doerFunc) Do(req *http.Request) (*http.Response, error) {
return d(req)
}
type metricWrapper struct {
now func() time.Time
queryLatency metrics.Histogram
}
func newMetricWrapper(now func() time.Time, queryLatency metrics.Histogram) (*metricWrapper, error) {
if now == nil {
now = time.Now
}
if queryLatency == nil {
return nil, errNilHistogram
}
return &metricWrapper{
now: now,
queryLatency: queryLatency,
}, nil
}
func (m *metricWrapper) roundTripper(next httpClient) httpClient {
return doerFunc(func(req *http.Request) (*http.Response, error) {
startTime := m.now()
resp, err := next.Do(req)
endTime := m.now()
code := networkError
if err == nil {
code = strconv.Itoa(resp.StatusCode)
}
// Adding request URI to identify the webhook in latency metric
code = req.RequestURI + "-" + code
// find time difference, add to metric
var latency = endTime.Sub(startTime)
m.queryLatency.With("code", code).Observe(latency.Seconds())
return resp, err
})
}