Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

client: Allow configuration of http client #1025

Merged
merged 3 commits into from Apr 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 26 additions & 1 deletion api/client.go
Expand Up @@ -17,6 +17,7 @@ package api
import (
"bytes"
"context"
"errors"
"net"
"net/http"
"net/url"
Expand All @@ -40,6 +41,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 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
// provided, DefaultRoundTripper will be used.
RoundTripper http.RoundTripper
Expand All @@ -52,6 +57,22 @@ func (cfg *Config) roundTripper() http.RoundTripper {
return cfg.RoundTripper
}

func (cfg *Config) client() http.Client {
kakkoyun marked this conversation as resolved.
Show resolved Hide resolved
if cfg.Client == nil {
return http.Client{
Transport: cfg.roundTripper(),
}
}
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
Expand All @@ -68,9 +89,13 @@ 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: http.Client{Transport: cfg.roundTripper()},
client: cfg.client(),
}, nil
}

Expand Down