Skip to content

Expose, or allow inserting, the http.Client used by the api.Client #932

@dsonck92

Description

@dsonck92

When querying Prometheus behind a proxy or authentication layer, certain extra authentication information may be necessary. Normally, this could be handled by giving a custom http.Client, however, the api.Client implementation httpClient wraps the http.Client and only exposes the address and http.RoundTripper to the user.

As per the go docs, the http.RoundTripper is explicitly not handling things like redirects, authentication or cookies and cannot be used to this end.

In my own project, I could work around it by creating my own implementation of the api.Client interface, essentially duplicating the existing code. But I think it would be beneficial to expose the internal http.Client in some way.

Potentially:

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 is allocated
	Client *http.Client

	// RoundTripper is used by the Client to drive HTTP requests, if no
        // client has been passed in as well. If not
	// provided, DefaultRoundTripper will be used.
	// Deprecated: set it directly on the Client instead
	RoundTripper http.RoundTripper
}

// ...

func (cfg *Config) client() *http.Client {
	if cfg.Client == nil {
		// Set the roundtripper for old code
		return &http.Client{
			Transport: cfg.roundTripper()
		}
	}
	return cfg.Client
}

// ...

// NewClient returns a new Client.
//
// It is safe to use the returned Client from multiple goroutines.
func NewClient(cfg Config) (Client, error) {
	u, err := url.Parse(cfg.Address)
	if err != nil {
		return nil, err
	}
	u.Path = strings.TrimRight(u.Path, "/")
	
	return &httpClient{
		endpoint: u,
		client:   *cfg.client(),
	}, nil
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions