From 269307accb81fbe697664893f229adc27f854669 Mon Sep 17 00:00:00 2001 From: "azat.muhammetamanov" Date: Wed, 7 Oct 2026 13:55:34 +0300 Subject: [PATCH] fix: prevent nil pointer panic and close response body in RunPushGatewayGatherer --- prometheus.go | 2 ++ prometheus_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/prometheus.go b/prometheus.go index 3e46796..2634543 100644 --- a/prometheus.go +++ b/prometheus.go @@ -425,7 +425,9 @@ 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.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/prometheus_test.go b/prometheus_test.go index 71882ad..451e91d 100644 --- a/prometheus_test.go +++ b/prometheus_test.go @@ -11,6 +11,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" "time" @@ -387,3 +388,31 @@ func unregisterDefaults(subsystem string) { Help: "The HTTP request sizes in bytes.", }) } + +func TestRunPushGatewayGatherer_UnreachableGateway(t *testing.T) { + // Start and immediately close a server so the URL refuses connections. + srv := httptest.NewServer(http.NotFoundHandler()) + url := srv.URL + srv.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + + var errCount int32 + config := PushGatewayConfig{ + PushGatewayURL: url, + PushInterval: 10 * time.Millisecond, + ErrorHandler: func(err error) error { + atomic.AddInt32(&errCount, 1) + return nil // keep running + }, + } + + err := RunPushGatewayGatherer(ctx, config) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected context deadline exceeded, got: %v", err) + } + if atomic.LoadInt32(&errCount) == 0 { + t.Fatal("expected ErrorHandler to be called for connection errors") + } +}