Skip to content

Commit 0bab4fd

Browse files
authored
push: Add PushContext and AddContext to Pusher (prometheus#1028)
Add PushContext and AddContext to Pusher, which are context-aware version of Push and Add respectively. They give a caller the ability to cancel an HTTP request. Signed-off-by: Tatsuhiro Tsujikawa <ttsujika@zlab.co.jp>
1 parent 06b6412 commit 0bab4fd

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

prometheus/push/push.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ package push
3636

3737
import (
3838
"bytes"
39+
"context"
3940
"encoding/base64"
4041
"errors"
4142
"fmt"
@@ -123,14 +124,28 @@ func New(url, job string) *Pusher {
123124
// Push returns the first error encountered by any method call (including this
124125
// one) in the lifetime of the Pusher.
125126
func (p *Pusher) Push() error {
126-
return p.push(http.MethodPut)
127+
return p.push(context.Background(), http.MethodPut)
128+
}
129+
130+
// PushContext is like Push but includes a context.
131+
//
132+
// If the context expires before HTTP request is complete, an error is returned.
133+
func (p *Pusher) PushContext(ctx context.Context) error {
134+
return p.push(ctx, http.MethodPut)
127135
}
128136

129137
// Add works like push, but only previously pushed metrics with the same name
130138
// (and the same job and other grouping labels) will be replaced. (It uses HTTP
131139
// method “POST” to push to the Pushgateway.)
132140
func (p *Pusher) Add() error {
133-
return p.push(http.MethodPost)
141+
return p.push(context.Background(), http.MethodPost)
142+
}
143+
144+
// AddContext is like Add but includes a context.
145+
//
146+
// If the context expires before HTTP request is complete, an error is returned.
147+
func (p *Pusher) AddContext(ctx context.Context) error {
148+
return p.push(ctx, http.MethodPost)
134149
}
135150

136151
// Gatherer adds a Gatherer to the Pusher, from which metrics will be gathered
@@ -233,7 +248,7 @@ func (p *Pusher) Delete() error {
233248
return nil
234249
}
235250

236-
func (p *Pusher) push(method string) error {
251+
func (p *Pusher) push(ctx context.Context, method string) error {
237252
if p.error != nil {
238253
return p.error
239254
}
@@ -260,7 +275,7 @@ func (p *Pusher) push(method string) error {
260275
}
261276
enc.Encode(mf)
262277
}
263-
req, err := http.NewRequest(method, p.fullURL(), buf)
278+
req, err := http.NewRequestWithContext(ctx, method, p.fullURL(), buf)
264279
if err != nil {
265280
return err
266281
}

0 commit comments

Comments
 (0)