change client to interface, allow override by other implementations (e.g. github.com/hashicorp/go-retryablehttp)

Signed-off-by: Roy Reshef <rreshef@densify.com>
This commit is contained in:
Roy Reshef 2023-11-22 15:44:29 -05:00
parent 80d3f0b5b3
commit 24d59e9b9b
2 changed files with 11 additions and 7 deletions

View File

@ -36,14 +36,18 @@ var DefaultRoundTripper http.RoundTripper = &http.Transport{
TLSHandshakeTimeout: 10 * time.Second, TLSHandshakeTimeout: 10 * time.Second,
} }
type HttpClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Config defines configuration parameters for a new client. // Config defines configuration parameters for a new client.
type Config struct { type Config struct {
// The address of the Prometheus to connect to. // The address of the Prometheus to connect to.
Address string Address string
// Client is used by the Client to drive HTTP requests. If not provided, // Client is used by the Client to drive HTTP requests. If not provided,
// a new one based on the provided RoundTripper (or DefaultRoundTripper) will be used. // a new http.Client based on the provided RoundTripper (or DefaultRoundTripper) will be used.
Client *http.Client Client HttpClient
// RoundTripper is used by the Client to drive HTTP requests. If not // RoundTripper is used by the Client to drive HTTP requests. If not
// provided, DefaultRoundTripper will be used. // provided, DefaultRoundTripper will be used.
@ -57,13 +61,13 @@ func (cfg *Config) roundTripper() http.RoundTripper {
return cfg.RoundTripper return cfg.RoundTripper
} }
func (cfg *Config) client() http.Client { func (cfg *Config) client() HttpClient {
if cfg.Client == nil { if cfg.Client == nil {
return http.Client{ return &http.Client{
Transport: cfg.roundTripper(), Transport: cfg.roundTripper(),
} }
} }
return *cfg.Client return cfg.Client
} }
func (cfg *Config) validate() error { func (cfg *Config) validate() error {
@ -101,7 +105,7 @@ func NewClient(cfg Config) (Client, error) {
type httpClient struct { type httpClient struct {
endpoint *url.URL endpoint *url.URL
client http.Client client HttpClient
} }
func (c *httpClient) URL(ep string, args map[string]string) *url.URL { func (c *httpClient) URL(ep string, args map[string]string) *url.URL {

View File

@ -105,7 +105,7 @@ func TestClientURL(t *testing.T) {
hclient := &httpClient{ hclient := &httpClient{
endpoint: ep, endpoint: ep,
client: http.Client{Transport: DefaultRoundTripper}, client: &http.Client{Transport: DefaultRoundTripper},
} }
u := hclient.URL(test.endpoint, test.args) u := hclient.URL(test.endpoint, test.args)