Skip to content

Commit f00866b

Browse files
Add url info on metrics attributes
1 parent 97df177 commit f00866b

2 files changed

Lines changed: 75 additions & 1 deletion

File tree

register_metrics_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package httpclient_test
2+
3+
import (
4+
"io"
5+
"net/http"
6+
"net/http/httptest"
7+
"sync"
8+
"testing"
9+
"time"
10+
11+
"github.com/globocom/httpclient"
12+
"github.com/stretchr/testify/assert"
13+
)
14+
15+
type mockMetrics struct {
16+
pushToSeriesCalls []string
17+
incrCounterCalls []string
18+
incrCounterWithAttrsCalls []struct {
19+
key string
20+
attrs map[string]string
21+
}
22+
lock sync.Mutex
23+
}
24+
25+
func (m *mockMetrics) PushToSeries(key string, value float64) {
26+
m.lock.Lock()
27+
defer m.lock.Unlock()
28+
m.pushToSeriesCalls = append(m.pushToSeriesCalls, key)
29+
}
30+
31+
func (m *mockMetrics) IncrCounter(key string) {
32+
m.lock.Lock()
33+
defer m.lock.Unlock()
34+
m.incrCounterCalls = append(m.incrCounterCalls, key)
35+
}
36+
37+
func (m *mockMetrics) IncrCounterWithAttrs(key string, attrs map[string]string) {
38+
m.lock.Lock()
39+
defer m.lock.Unlock()
40+
m.incrCounterWithAttrsCalls = append(m.incrCounterWithAttrsCalls, struct {
41+
key string
42+
attrs map[string]string
43+
}{key, attrs})
44+
}
45+
46+
func TestHTTPClient_MetricsIntegration(t *testing.T) {
47+
metrics := &mockMetrics{}
48+
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
49+
rw.WriteHeader(http.StatusOK)
50+
rw.Write([]byte("OK"))
51+
}))
52+
defer server.Close()
53+
54+
client := httpclient.NewHTTPClient(
55+
&httpclient.LoggerAdapter{Writer: io.Discard},
56+
httpclient.WithHostURL(server.URL),
57+
httpclient.WithMetrics(metrics),
58+
)
59+
60+
req := client.NewRequest()
61+
resp, err := req.Get("/")
62+
assert.NoError(t, err)
63+
assert.NotNil(t, resp)
64+
65+
assert.Eventually(t, func() bool {
66+
metrics.lock.Lock()
67+
defer metrics.lock.Unlock()
68+
return len(metrics.pushToSeriesCalls) > 0 && len(metrics.incrCounterCalls) > 0 && len(metrics.incrCounterWithAttrsCalls) > 0
69+
}, time.Second, 100*time.Millisecond)
70+
}

request.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,12 @@ func registerMetrics(key string, metrics Metrics, f func() (*Response, error)) (
150150

151151
if metrics != nil {
152152
go func(resp *Response, err error) {
153-
attrs := map[string]string{}
153+
var attrs map[string]string
154154
if resp != nil {
155+
attrs = map[string]string{
156+
"host": resp.Request().HostURL().Host,
157+
"path": resp.Request().HostURL().Path,
158+
}
155159
metrics.PushToSeries(fmt.Sprintf("%s.%s", key, "response_time"), resp.ResponseTime().Seconds())
156160
if resp.statusCode != 0 {
157161
metrics.IncrCounter(fmt.Sprintf("%s.status.%d", key, resp.StatusCode()))

0 commit comments

Comments
 (0)