Skip to content

Commit

Permalink
client: Allow configuration of http client
Browse files Browse the repository at this point in the history
Signed-off-by: yolossn <nssvlr@gmail.com>
  • Loading branch information
yolossn committed Apr 12, 2022
1 parent 29e8191 commit efe94be
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion api/client.go
Expand Up @@ -17,6 +17,7 @@ package api
import (
"bytes"
"context"
"fmt"
"net"
"net/http"
"net/url"
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
}

Expand Down

0 comments on commit efe94be

Please sign in to comment.