Merge pull request #178 from prometheus/ctx

Use ctxhttp package for cancelable requests
This commit is contained in:
Fabian Reinartz 2015-10-02 13:48:55 +02:00
commit b6cad5edaf
1 changed files with 2 additions and 23 deletions

View File

@ -29,6 +29,7 @@ import (
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"golang.org/x/net/context" "golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
) )
const ( const (
@ -134,29 +135,7 @@ func (c *httpClient) url(ep string, args map[string]string) *url.URL {
} }
func (c *httpClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { func (c *httpClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
type roundTripResponse struct { resp, err := ctxhttp.Do(ctx, &http.Client{Transport: c.transport}, req)
resp *http.Response
err error
}
rtchan := make(chan roundTripResponse, 1)
go func() {
resp, err := c.transport.RoundTrip(req)
rtchan <- roundTripResponse{resp: resp, err: err}
close(rtchan)
}()
var resp *http.Response
var err error
select {
case rtresp := <-rtchan:
resp, err = rtresp.resp, rtresp.err
case <-ctx.Done():
// Cancel request and wait until it terminated.
c.transport.CancelRequest(req)
resp, err = (<-rtchan).resp, ctx.Err()
}
defer func() { defer func() {
if resp != nil { if resp != nil {