diff --git a/api/client.go b/api/client.go index 1413f65fe..611eb983e 100644 --- a/api/client.go +++ b/api/client.go @@ -17,6 +17,7 @@ package api import ( "bytes" "context" + "fmt" "net" "net/http" "net/url" @@ -35,11 +36,20 @@ var DefaultRoundTripper http.RoundTripper = &http.Transport{ TLSHandshakeTimeout: 10 * time.Second, } +// DefaultClient is used if no Client is set in Config. +var DefaultClient http.Client = http.Client{ + Transport: DefaultRoundTripper, +} + // Config defines configuration parameters for a new client. type Config struct { // The address of the Prometheus to connect to. Address string + // Client is used by the Client to drive HTTP requests. If not provided, + // DefaultClient will be used. + Client *http.Client + // RoundTripper is used by the Client to drive HTTP requests. If not // provided, DefaultRoundTripper will be used. RoundTripper http.RoundTripper @@ -52,6 +62,13 @@ func (cfg *Config) roundTripper() http.RoundTripper { return cfg.RoundTripper } +func (cfg *Config) client() http.Client { + if cfg.Client == nil { + return DefaultClient + } + return *cfg.Client +} + // Client is the interface for an API client. type Client interface { URL(ep string, args map[string]string) *url.URL @@ -68,9 +85,13 @@ func NewClient(cfg Config) (Client, error) { } u.Path = strings.TrimRight(u.Path, "/") + if cfg.Client != nil && cfg.RoundTripper != nil { + return nil, fmt.Errorf("both client and roundTripper cannot be configured") + } + return &httpClient{ endpoint: u, - client: http.Client{Transport: cfg.roundTripper()}, + client: cfg.client(), }, nil }