forked from mirror/client_golang
client: Allow configuration of http client (#1025)
* client: Allow configuration of http client Signed-off-by: yolossn <nssvlr@gmail.com> * Add api.Config validation to prevent confusion Update config documentation Signed-off-by: Kemal Akkoyun <kakkoyun@gmail.com> Co-authored-by: Kemal Akkoyun <kakkoyun@gmail.com>
This commit is contained in:
parent
efe8e6fac8
commit
404809144b
|
@ -17,6 +17,7 @@ package api
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
@ -40,6 +41,10 @@ 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,
|
||||||
|
// 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
|
// RoundTripper is used by the Client to drive HTTP requests. If not
|
||||||
// provided, DefaultRoundTripper will be used.
|
// provided, DefaultRoundTripper will be used.
|
||||||
RoundTripper http.RoundTripper
|
RoundTripper http.RoundTripper
|
||||||
|
@ -52,6 +57,22 @@ func (cfg *Config) roundTripper() http.RoundTripper {
|
||||||
return cfg.RoundTripper
|
return cfg.RoundTripper
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cfg *Config) client() http.Client {
|
||||||
|
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.
|
// Client is the interface for an API client.
|
||||||
type Client interface {
|
type Client interface {
|
||||||
URL(ep string, args map[string]string) *url.URL
|
URL(ep string, args map[string]string) *url.URL
|
||||||
|
@ -68,9 +89,13 @@ func NewClient(cfg Config) (Client, error) {
|
||||||
}
|
}
|
||||||
u.Path = strings.TrimRight(u.Path, "/")
|
u.Path = strings.TrimRight(u.Path, "/")
|
||||||
|
|
||||||
|
if err := cfg.validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
return &httpClient{
|
return &httpClient{
|
||||||
endpoint: u,
|
endpoint: u,
|
||||||
client: http.Client{Transport: cfg.roundTripper()},
|
client: cfg.client(),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue