api: uses context from net/http

This commit removes the now unnecessary CancelableTransport and rely on
the net/http context support.
This commit is contained in:
André Carvalho 2017-04-20 10:31:18 -03:00
parent 11fae2ef0c
commit 09dcce7042
No known key found for this signature in database
GPG Key ID: 440C9C458D3A1E61
2 changed files with 22 additions and 28 deletions

View File

@ -23,19 +23,10 @@ import (
"path"
"strings"
"time"
"golang.org/x/net/context/ctxhttp"
)
// CancelableTransport is like net.Transport but provides
// per-request cancelation functionality.
type CancelableTransport interface {
http.RoundTripper
CancelRequest(req *http.Request)
}
// DefaultTransport is used if no Transport is set in Config.
var DefaultTransport CancelableTransport = &http.Transport{
// DefaultRoundTripper is used if no RoundTripper is set in Config.
var DefaultRoundTripper http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
@ -49,16 +40,16 @@ type Config struct {
// The address of the Prometheus to connect to.
Address string
// Transport is used by the Client to drive HTTP requests. If not
// provided, DefaultTransport will be used.
Transport CancelableTransport
// RoundTripper is used by the Client to drive HTTP requests. If not
// provided, DefaultRoundTripper will be used.
RoundTripper http.RoundTripper
}
func (cfg *Config) transport() CancelableTransport {
if cfg.Transport == nil {
return DefaultTransport
func (cfg *Config) roundTripper() http.RoundTripper {
if cfg.RoundTripper == nil {
return DefaultRoundTripper
}
return cfg.Transport
return cfg.RoundTripper
}
// Client is the interface for an API client.
@ -79,13 +70,13 @@ func New(cfg Config) (Client, error) {
return &httpClient{
endpoint: u,
transport: cfg.transport(),
client: http.Client{Transport: cfg.roundTripper()},
}, nil
}
type httpClient struct {
endpoint *url.URL
transport CancelableTransport
client http.Client
}
func (c *httpClient) URL(ep string, args map[string]string) *url.URL {
@ -103,8 +94,10 @@ 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) {
resp, err := ctxhttp.Do(ctx, &http.Client{Transport: c.transport}, req)
if ctx != nil {
req = req.WithContext(ctx)
}
resp, err := c.client.Do(req)
defer func() {
if resp != nil {
resp.Body.Close()

View File

@ -14,14 +14,15 @@
package api
import (
"net/http"
"net/url"
"testing"
)
func TestConfig(t *testing.T) {
c := Config{}
if c.transport() != DefaultTransport {
t.Fatalf("expected default transport for nil Transport field")
if c.roundTripper() != DefaultRoundTripper {
t.Fatalf("expected default roundtripper for nil RoundTripper field")
}
}
@ -100,7 +101,7 @@ func TestClientURL(t *testing.T) {
hclient := &httpClient{
endpoint: ep,
transport: DefaultTransport,
client: http.Client{Transport: DefaultRoundTripper},
}
u := hclient.URL(test.endpoint, test.args)