From b5f1e9eebb533ed0649b2d967376702396dbdb24 Mon Sep 17 00:00:00 2001 From: yolossn Date: Mon, 18 Apr 2022 18:22:20 +0530 Subject: [PATCH 1/2] client: Allow configuration of http client Signed-off-by: yolossn --- api/client.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/api/client.go b/api/client.go index 1413f65fe..f1ba7c83d 100644 --- a/api/client.go +++ b/api/client.go @@ -40,6 +40,10 @@ 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, + // a new one is created. + 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 +56,15 @@ func (cfg *Config) roundTripper() http.RoundTripper { return cfg.RoundTripper } +func (cfg *Config) client() http.Client { + if cfg.Client == nil { + return http.Client{ + Transport: cfg.roundTripper(), + } + } + return *cfg.Client +} + // Client is the interface for an API client. type Client interface { URL(ep string, args map[string]string) *url.URL @@ -70,7 +83,7 @@ func NewClient(cfg Config) (Client, error) { return &httpClient{ endpoint: u, - client: http.Client{Transport: cfg.roundTripper()}, + client: cfg.client(), }, nil } From 33ac4729e73ae528f641e56885e88d5be5d0da78 Mon Sep 17 00:00:00 2001 From: Kemal Akkoyun Date: Thu, 21 Apr 2022 07:44:24 +0200 Subject: [PATCH 2/2] Add api.Config validation to prevent confusion Update config documentation Signed-off-by: Kemal Akkoyun --- api/client.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/api/client.go b/api/client.go index f1ba7c83d..c91cf0c16 100644 --- a/api/client.go +++ b/api/client.go @@ -17,6 +17,7 @@ package api import ( "bytes" "context" + "errors" "net" "net/http" "net/url" @@ -41,7 +42,7 @@ type Config struct { Address string // Client is used by the Client to drive HTTP requests. If not provided, - // a new one is created. + // a new one based on the provided RoundTripper (or DefaultRoundTripper) will be used. Client *http.Client // RoundTripper is used by the Client to drive HTTP requests. If not @@ -65,6 +66,13 @@ func (cfg *Config) client() http.Client { return *cfg.Client } +func (cfg *Config) validate() error { + if cfg.Client != nil && cfg.RoundTripper != nil { + return errors.New("api.Config.RoundTripper and api.Config.Client are mutually exclusive") + } + return nil +} + // Client is the interface for an API client. type Client interface { URL(ep string, args map[string]string) *url.URL @@ -81,6 +89,10 @@ func NewClient(cfg Config) (Client, error) { } u.Path = strings.TrimRight(u.Path, "/") + if err := cfg.validate(); err != nil { + return nil, err + } + return &httpClient{ endpoint: u, client: cfg.client(),