diff --git a/client/transport/transport.go b/client/transport/transport.go index 931f59b6..3b8542e8 100644 --- a/client/transport/transport.go +++ b/client/transport/transport.go @@ -40,7 +40,13 @@ func (m *metricsTransport) RoundTrip(req *http.Request) (*http.Response, error) startTime := time.Now() size := req.ContentLength + + var statusCode int resp, err := m.transport.RoundTrip(req) + if err == nil { + statusCode = resp.StatusCode + } + duration := time.Since(startTime) valueFromCtx := req.Context().Value(request.ContextKey) @@ -50,7 +56,7 @@ func (m *metricsTransport) RoundTrip(req *http.Request) (*http.Response, error) topic := fmt.Sprintf("%s", valueFromCtx) m.statusMetrics.AddIndexingData(metrics.ArgsAddIndexingData{ - StatusCode: resp.StatusCode, + StatusCode: statusCode, GotError: err != nil, MessageLen: uint64(size), Topic: topic, diff --git a/client/transport/transport_test.go b/client/transport/transport_test.go index 31c78ef9..8be7b196 100644 --- a/client/transport/transport_test.go +++ b/client/transport/transport_test.go @@ -3,6 +3,7 @@ package transport import ( "bytes" "context" + "errors" "net/http" "testing" @@ -34,6 +35,30 @@ func TestMetricsTransport_NilRequest(t *testing.T) { require.Equal(t, errNilRequest, err) } +func TestMetricsTransport_RoundTripNilResponseShouldWork(t *testing.T) { + t.Parallel() + + metricsHandler := metrics.NewStatusMetrics() + transportHandler, _ := NewMetricsTransport(metricsHandler) + + testErr := errors.New("test") + transportHandler.transport = &mock.TransportMock{ + Response: nil, + Err: testErr, + } + + testTopic := "test" + contextWithValue := context.WithValue(context.Background(), request.ContextKey, testTopic) + req, _ := http.NewRequestWithContext(contextWithValue, http.MethodGet, "dummy", bytes.NewBuffer([]byte("test"))) + + _, _ = transportHandler.RoundTrip(req) + + metricsMap := metricsHandler.GetMetrics() + require.Equal(t, uint64(1), metricsMap[testTopic].OperationsCount) + require.Equal(t, uint64(1), metricsMap[testTopic].TotalErrorsCount) + require.Equal(t, uint64(4), metricsMap[testTopic].TotalData) +} + func TestMetricsTransport_RoundTrip(t *testing.T) { t.Parallel()