From ff72cb46064df14df947537b5beac093a65d7dc9 Mon Sep 17 00:00:00 2001 From: sarankumar1325 <120080287+sarankumar1325@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:48:48 +0000 Subject: [PATCH] fix(echoprometheus): don't panic when push gateway is unreachable When client.Do failed and the ErrorHandler returned nil (the default), RunPushGatewayGatherer fell through to res.StatusCode with a nil response and panicked. Skip to the next tick instead, and drain and close the response body so connections are reused. Signed-off-by: sarankumar1325 <120080287+sarankumar1325@users.noreply.github.com> --- echoprometheus/prometheus.go | 3 +++ echoprometheus/prometheus_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/echoprometheus/prometheus.go b/echoprometheus/prometheus.go index 5e4327a..f184d83 100644 --- a/echoprometheus/prometheus.go +++ b/echoprometheus/prometheus.go @@ -444,7 +444,10 @@ func RunPushGatewayGatherer(ctx context.Context, config PushGatewayConfig) error if hErr := config.ErrorHandler(fmt.Errorf("error sending to push gateway: %w", err)); hErr != nil { return hErr } + continue // res is nil when client.Do returns an error } + _, _ = io.Copy(io.Discard, res.Body) + _ = res.Body.Close() if res.StatusCode != http.StatusOK { if hErr := config.ErrorHandler(echo.NewHTTPError(res.StatusCode, "post metrics request did not succeed")); hErr != nil { return hErr diff --git a/echoprometheus/prometheus_test.go b/echoprometheus/prometheus_test.go index c0333d4..8da0713 100644 --- a/echoprometheus/prometheus_test.go +++ b/echoprometheus/prometheus_test.go @@ -340,6 +340,32 @@ func TestRunPushGatewayGatherer(t *testing.T) { unregisterDefaults("myapp") } +func TestRunPushGatewayGatherer_unreachableGatewayDoesNotPanic(t *testing.T) { + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + unreachableURL := svr.URL + svr.Close() // connections to this URL now fail, so client.Do returns an error and a nil response + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + + var handledErrs []error + config := PushGatewayConfig{ + PushGatewayURL: unreachableURL, + PushInterval: 10 * time.Millisecond, + Gatherer: prometheus.NewRegistry(), + ErrorHandler: func(err error) error { + handledErrs = append(handledErrs, err) + return nil // keep pushing, like the default ErrorHandler + }, + } + err := RunPushGatewayGatherer(ctx, config) + + assert.ErrorIs(t, err, context.DeadlineExceeded) + if assert.NotEmpty(t, handledErrs) { + assert.ErrorContains(t, handledErrs[0], "error sending to push gateway") + } +} + // TestSetPathFor404NoMatchingRoute tests that the url is not included in the metric when // the 404 response is due to no matching route func TestSetPathFor404NoMatchingRoute(t *testing.T) {