Skip to content

Commit 9ac3af8

Browse files
committed
client: Allow configuration of http client
Signed-off-by: yolossn <[email protected]>
1 parent 29e8191 commit 9ac3af8

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

api/client.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package api
1717
import (
1818
"bytes"
1919
"context"
20+
"fmt"
2021
"net"
2122
"net/http"
2223
"net/url"
@@ -35,11 +36,20 @@ var DefaultRoundTripper http.RoundTripper = &http.Transport{
3536
TLSHandshakeTimeout: 10 * time.Second,
3637
}
3738

39+
// DefaultClient is used if no Client is set in Config.
40+
var DefaultClient http.Client = http.Client{
41+
Transport: DefaultRoundTripper,
42+
}
43+
3844
// Config defines configuration parameters for a new client.
3945
type Config struct {
4046
// The address of the Prometheus to connect to.
4147
Address string
4248

49+
// Client is used by the Client to drive HTTP requests. If not provided,
50+
// DefaultClient will be used.
51+
Client *http.Client
52+
4353
// RoundTripper is used by the Client to drive HTTP requests. If not
4454
// provided, DefaultRoundTripper will be used.
4555
RoundTripper http.RoundTripper
@@ -52,6 +62,13 @@ func (cfg *Config) roundTripper() http.RoundTripper {
5262
return cfg.RoundTripper
5363
}
5464

65+
func (cfg *Config) client() http.Client {
66+
if cfg.Client == nil {
67+
return DefaultClient
68+
}
69+
return *cfg.Client
70+
}
71+
5572
// Client is the interface for an API client.
5673
type Client interface {
5774
URL(ep string, args map[string]string) *url.URL
@@ -68,9 +85,13 @@ func NewClient(cfg Config) (Client, error) {
6885
}
6986
u.Path = strings.TrimRight(u.Path, "/")
7087

88+
if cfg.Client != nil && cfg.RoundTripper != nil {
89+
return nil, fmt.Errorf("both client and roundTripper cannot be configured")
90+
}
91+
7192
return &httpClient{
7293
endpoint: u,
73-
client: http.Client{Transport: cfg.roundTripper()},
94+
client: cfg.client(),
7495
}, nil
7596
}
7697

0 commit comments

Comments
 (0)