The config package provides configuration structures and utilities for HTTP clients with comprehensive support for authentication (Basic, Bearer, OAuth2), TLS, proxies, and custom headers.
import "github.com/prometheus/common/config"This package offers a complete HTTP client configuration system used across Prometheus components. It supports multiple authentication methods, flexible TLS configuration, proxy settings, custom headers, and secret management. All configuration can be loaded from YAML files or constructed programmatically.
const secretToken = "<secret>"Token used to represent masked secrets in marshaled output.
var MarshalSecretValue = falseControls whether Secret values are exposed in marshaling. When false (default), secrets are masked as <secret>.
var DefaultHTTPClientConfig = HTTPClientConfig{
FollowRedirects: true,
EnableHTTP2: true,
}Default HTTP client configuration.
var ReservedHeaders map[string]struct{}HTTP headers reserved by Prometheus and not allowed in custom header configurations.
var TLSVersions map[string]TLSVersionMap of TLS version names to constants (e.g., "TLS10" -> tls.VersionTLS10).
type Secret stringA secret string that is masked when marshaling to prevent accidental exposure in logs or configs.
func (s Secret) MarshalYAML() (interface{}, error)Marshals as <secret> unless MarshalSecretValue is true.
func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals secret from YAML.
func (s Secret) MarshalJSON() ([]byte, error)Marshals as <secret> unless MarshalSecretValue is true.
type URL struct {
*url.URL
}URL wrapper with custom marshaling/unmarshaling and redaction support.
func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals URL from YAML.
func (u URL) MarshalYAML() (interface{}, error)Marshals URL as YAML string.
func (u *URL) Redacted() stringReturns URL with password replaced by "xxxxx".
func (u *URL) UnmarshalJSON(data []byte) errorUnmarshals URL from JSON.
func (u URL) MarshalJSON() ([]byte, error)Marshals URL as JSON string.
type BasicAuth struct {
Username string
UsernameFile string
UsernameRef string
Password Secret
PasswordFile string
PasswordRef string
}HTTP Basic Authentication configuration. Supports inline values, files, and secret references.
func (a *BasicAuth) SetDirectory(dir string)Joins relative file paths with dir.
func (a *BasicAuth) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals from YAML with validation.
type Authorization struct {
Type string
Credentials Secret
CredentialsFile string
CredentialsRef string
}HTTP Authorization header configuration for Bearer and custom authentication schemes.
func (a *Authorization) SetDirectory(dir string)Joins relative file paths with dir.
type OAuth2 struct {
ClientID string
ClientSecret Secret
ClientSecretFile string
ClientSecretRef string
ClientCertificateKeyID string
ClientCertificateKey Secret
ClientCertificateKeyFile string
ClientCertificateKeyRef string
GrantType string
SignatureAlgorithm string
Iss string
Audience string
Claims map[string]interface{}
Scopes []string
TokenURL string
EndpointParams map[string]string
TLSConfig TLSConfig
ProxyConfig ProxyConfig
}OAuth2 authentication configuration supporting multiple grant types including JWT bearer.
func (o *OAuth2) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals from YAML.
func (o *OAuth2) UnmarshalJSON(data []byte) errorUnmarshals from JSON.
func (o *OAuth2) SetDirectory(dir string)Joins relative file paths with dir.
type TLSVersion uint16TLS protocol version.
func (v *TLSVersion) UnmarshalYAML(unmarshal func(interface{}) error) errorfunc (v TLSVersion) MarshalYAML() (interface{}, error)func (v *TLSVersion) UnmarshalJSON(data []byte) errorfunc (v TLSVersion) MarshalJSON() ([]byte, error)func (v *TLSVersion) String() stringReturns string representation of TLS version.
type TLSRoundTripperSettings struct {
CA SecretReader
Cert SecretReader
Key SecretReader
}Settings for TLS RoundTripper configuration including CA, certificate, and key readers.
type TLSConfig struct {
CA string
Cert string
Key Secret
CAFile string
CertFile string
KeyFile string
CARef string
CertRef string
KeyRef string
ServerName string
InsecureSkipVerify bool
MinVersion TLSVersion
MaxVersion TLSVersion
}TLS/SSL configuration with support for inline certificates, files, and secret references.
func (c *TLSConfig) SetDirectory(dir string)Joins relative file paths with dir.
func (c *TLSConfig) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals from YAML with validation.
func (c *TLSConfig) Validate() errorValidates the TLS configuration.
type ProxyHeader map[string][]SecretHTTP headers for proxy CONNECT requests.
func (h *ProxyHeader) HTTPHeader() http.HeaderConverts to standard http.Header.
type ProxyConfig struct {
ProxyURL URL
NoProxy string
ProxyFromEnvironment bool
ProxyConnectHeader ProxyHeader
}HTTP proxy configuration with environment variable support.
func (c ProxyConfig) Validate() errorValidates the proxy configuration.
func (c *ProxyConfig) Proxy() func(*http.Request) (*url.URL, error)Returns a proxy URL function for use with http.Transport.
func (c *ProxyConfig) GetProxyConnectHeader() http.HeaderReturns headers to send in CONNECT requests.
type Header struct {
Values []string
Secrets []Secret
Files []string
}Single HTTP header with multiple value sources.
func (h *Header) SetDirectory(dir string)Joins relative file paths with dir.
type Headers struct {
Headers map[string]Header
}Custom HTTP headers configuration.
func (h Headers) MarshalJSON() ([]byte, error)func (h *Headers) SetDirectory(dir string)Joins relative file paths with dir.
func (h *Headers) Validate() errorValidates header configuration.
type HTTPClientConfig struct {
BasicAuth *BasicAuth
Authorization *Authorization
OAuth2 *OAuth2
BearerToken Secret
BearerTokenFile string
TLSConfig TLSConfig
FollowRedirects bool
EnableHTTP2 bool
ProxyConfig ProxyConfig
HTTPHeaders *Headers
}Complete HTTP client configuration with authentication, TLS, proxy, and header support.
func (c *HTTPClientConfig) SetDirectory(dir string)Joins relative file paths with dir.
func (c *HTTPClientConfig) Validate() errorValidates the configuration.
func (c *HTTPClientConfig) UnmarshalYAML(unmarshal func(interface{}) error) errorUnmarshals from YAML.
func (c *HTTPClientConfig) UnmarshalJSON(data []byte) errorUnmarshals from JSON.
func (c HTTPClientConfig) String() stringReturns string representation.
type SecretReader interface {
Fetch(ctx context.Context) (string, error)
Description() string
Immutable() bool
}Interface for reading secrets from various sources.
type SecretManager interface {
Fetch(ctx context.Context, secretRef string) (string, error)
}Interface for fetching secrets from external sources.
type DirectorySetter interface {
SetDirectory(dir string)
}Interface for types that support setting a base directory for relative paths.
func LoadHTTPConfig(s string) (*HTTPClientConfig, error)Parses YAML string into HTTPClientConfig.
Parameters:
s - YAML configuration stringReturns: (*HTTPClientConfig, error)
func LoadHTTPConfigFile(filename string) (*HTTPClientConfig, []byte, error)Parses YAML file into HTTPClientConfig.
Parameters:
filename - Path to YAML configuration fileReturns: (*HTTPClientConfig, []byte, error) - Config, raw bytes, error
func NewClientFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HTTPClientOption) (*http.Client, error)Creates a new HTTP client from configuration.
Parameters:
cfg - HTTP client configurationname - Name for the client (used in User-Agent)optFuncs - Optional configuration functionsReturns: (*http.Client, error)
func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HTTPClientOption) (http.RoundTripper, error)Creates a new RoundTripper from configuration.
Parameters:
cfg - HTTP client configurationname - Name for the clientoptFuncs - Optional configuration functionsReturns: (http.RoundTripper, error)
func NewRoundTripperFromConfigWithContext(ctx context.Context, cfg HTTPClientConfig, name string, optFuncs ...HTTPClientOption) (http.RoundTripper, error)Creates a new RoundTripper from configuration with context for secret fetching.
Parameters:
ctx - Context for the operationcfg - HTTP client configurationname - Name for the clientoptFuncs - Optional configuration functionsReturns: (http.RoundTripper, error)
func NewTLSConfig(cfg *TLSConfig, optFuncs ...TLSConfigOption) (*tls.Config, error)Creates a new TLS configuration.
Parameters:
cfg - TLS configurationoptFuncs - Optional configuration functionsReturns: (*tls.Config, error)
func NewTLSConfigWithContext(ctx context.Context, cfg *TLSConfig, optFuncs ...TLSConfigOption) (*tls.Config, error)Creates a new TLS configuration with context.
Parameters:
ctx - Context for the operationcfg - TLS configurationoptFuncs - Optional configuration functionsReturns: (*tls.Config, error)
func NewTLSRoundTripper(cfg *tls.Config, settings TLSRoundTripperSettings, newRT func(*tls.Config) (http.RoundTripper, error)) (http.RoundTripper, error)Creates a new TLS RoundTripper.
Parameters:
cfg - TLS configurationsettings - RoundTripper settingsnewRT - Function to create the underlying RoundTripperReturns: (http.RoundTripper, error)
func NewTLSRoundTripperWithContext(ctx context.Context, cfg *tls.Config, settings TLSRoundTripperSettings, newRT func(*tls.Config) (http.RoundTripper, error)) (http.RoundTripper, error)Creates a new TLS RoundTripper with context.
Parameters:
ctx - Context for the operationcfg - TLS configurationsettings - RoundTripper settingsnewRT - Function to create the underlying RoundTripperReturns: (http.RoundTripper, error)
func NewHeadersRoundTripper(config *Headers, next http.RoundTripper) http.RoundTripperCreates a RoundTripper that adds custom headers to requests.
Parameters:
config - Headers configurationnext - Next RoundTripper in chainReturns: http.RoundTripper
func NewAuthorizationCredentialsRoundTripper(authType string, authCredentials SecretReader, rt http.RoundTripper) http.RoundTripperCreates a RoundTripper with Authorization header.
Parameters:
authType - Authorization type (e.g., "Bearer")authCredentials - Credentials readerrt - Next RoundTripper in chainReturns: http.RoundTripper
func NewBasicAuthRoundTripper(username, password SecretReader, rt http.RoundTripper) http.RoundTripperCreates a RoundTripper with Basic authentication.
Parameters:
username - Username readerpassword - Password readerrt - Next RoundTripper in chainReturns: http.RoundTripper
func NewOAuth2RoundTripper(oauthCredential SecretReader, config *OAuth2, next http.RoundTripper, opts *httpClientOptions) http.RoundTripperCreates a RoundTripper with OAuth2 authentication.
Parameters:
oauthCredential - OAuth credential readerconfig - OAuth2 configurationnext - Next RoundTripper in chainopts - HTTP client optionsReturns: http.RoundTripper
func NewUserAgentRoundTripper(userAgent string, rt http.RoundTripper) http.RoundTripperCreates a RoundTripper that sets User-Agent header.
Parameters:
userAgent - User-Agent stringrt - Next RoundTripper in chainReturns: http.RoundTripper
func NewHostRoundTripper(host string, rt http.RoundTripper) http.RoundTripperCreates a RoundTripper that overrides the Host header.
Parameters:
host - Host header valuert - Next RoundTripper in chainReturns: http.RoundTripper
func NewInlineSecret(text string) *InlineSecretCreates a new inline secret.
Parameters:
text - Secret textReturns: *InlineSecret
func NewFileSecret(file string) *FileSecretCreates a new file-based secret.
Parameters:
file - Path to secret fileReturns: *FileSecret
type InlineSecret struct {
// contains filtered or unexported fields
}Inline secret implementation that stores secret text in memory.
func (s *InlineSecret) Fetch(ctx context.Context) (string, error)Returns the inline secret text.
func (s *InlineSecret) Description() stringReturns "inline" as the description.
func (s *InlineSecret) Immutable() boolReturns true since inline secrets are immutable.
type FileSecret struct {
// contains filtered or unexported fields
}File-based secret implementation that reads secret from a file.
func (s *FileSecret) Fetch(ctx context.Context) (string, error)Reads and returns the secret from the file.
func (s *FileSecret) Description() stringReturns "file <path>" as the description.
func (s *FileSecret) Immutable() boolReturns false since file secrets can change.
func JoinDir(dir, path string) stringJoins dir and path if path is relative; returns path unchanged if absolute.
Parameters:
dir - Base directorypath - Path to joinReturns: Joined path
func WithDialContextFunc(fn DialContextFunc) HTTPClientOptionSets custom dial context function.
func WithNewTLSConfigFunc(newTLSConfigFunc NewTLSConfigFunc) HTTPClientOptionSets custom TLS config creation function.
func WithKeepAlivesDisabled() HTTPClientOptionDisables HTTP keep-alives.
func WithHTTP2Disabled() HTTPClientOptionDisables HTTP/2.
func WithIdleConnTimeout(timeout time.Duration) HTTPClientOptionSets idle connection timeout.
func WithUserAgent(ua string) HTTPClientOptionSets User-Agent header.
func WithHost(host string) HTTPClientOptionSets Host header.
func WithSecretManager(manager SecretManager) SecretManagerOptionSets secret manager for fetching secrets from external sources.
type HTTPClientOption interface{}Option function for HTTP client configuration.
type TLSConfigOption interface{}Option function for TLS configuration.
type SecretManagerOption interface{}Option that implements both HTTPClientOption and TLSConfigOption.
type DialContextFunc func(context.Context, string, string) (net.Conn, error)Function type for custom dial context.
type NewTLSConfigFunc func(context.Context, *TLSConfig, ...TLSConfigOption) (*tls.Config, error)Function type for custom TLS config creation.
type JwtGrantTypeConfig struct {
Iss string
PrivateKey []byte
SigningAlgorithm *jwt.SigningMethodRSA
PrivateKeyID string
Subject string
Scopes []string
TokenURL string
EndpointParams url.Values
Expires time.Duration
Audience string
PrivateClaims map[string]any
}JWT grant type configuration for OAuth2.
func (c *JwtGrantTypeConfig) TokenSource(ctx context.Context) oauth2.TokenSourceReturns an OAuth2 token source.
func (c *JwtGrantTypeConfig) Client(ctx context.Context) *http.ClientReturns a configured HTTP client.
package main
import (
"fmt"
"io"
"github.com/prometheus/common/config"
)
func main() {
cfg := config.HTTPClientConfig{
FollowRedirects: true,
EnableHTTP2: true,
}
client, err := config.NewClientFromConfig(cfg, "my-app")
if err != nil {
panic(err)
}
resp, err := client.Get("https://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}package main
import (
"github.com/prometheus/common/config"
)
func main() {
cfg := config.HTTPClientConfig{
TLSConfig: config.TLSConfig{
CAFile: "/path/to/ca.pem",
CertFile: "/path/to/cert.pem",
KeyFile: "/path/to/key.pem",
ServerName: "example.com",
InsecureSkipVerify: false,
},
}
client, err := config.NewClientFromConfig(cfg, "secure-client")
if err != nil {
panic(err)
}
// Use client...
}package main
import (
"github.com/prometheus/common/config"
)
func main() {
cfg := config.HTTPClientConfig{
BasicAuth: &config.BasicAuth{
Username: "user",
Password: config.Secret("password"),
},
}
client, err := config.NewClientFromConfig(cfg, "basic-auth-client")
if err != nil {
panic(err)
}
// Use client with Basic Auth...
}package main
import (
"github.com/prometheus/common/config"
)
func main() {
cfg := config.HTTPClientConfig{
BearerTokenFile: "/var/run/secrets/token",
}
client, err := config.NewClientFromConfig(cfg, "bearer-client")
if err != nil {
panic(err)
}
// Token is automatically read from file and refreshed
}package main
import (
"github.com/prometheus/common/config"
)
func main() {
cfg := config.HTTPClientConfig{
OAuth2: &config.OAuth2{
ClientID: "my-client-id",
ClientSecret: config.Secret("my-client-secret"),
TokenURL: "https://oauth.example.com/token",
Scopes: []string{"read", "write"},
},
}
client, err := config.NewClientFromConfig(cfg, "oauth2-client")
if err != nil {
panic(err)
}
// OAuth2 tokens are automatically managed
}package main
import (
"net/url"
"github.com/prometheus/common/config"
)
func main() {
proxyURL, _ := url.Parse("http://proxy.example.com:8080")
cfg := config.HTTPClientConfig{
ProxyConfig: config.ProxyConfig{
ProxyURL: config.URL{URL: proxyURL},
NoProxy: "localhost,127.0.0.1",
},
}
client, err := config.NewClientFromConfig(cfg, "proxy-client")
if err != nil {
panic(err)
}
// Requests use proxy except for NoProxy hosts
}package main
import (
"github.com/prometheus/common/config"
)
func main() {
cfg := config.HTTPClientConfig{
HTTPHeaders: &config.Headers{
Headers: map[string]config.Header{
"X-Custom-Header": {
Values: []string{"value1", "value2"},
},
"X-API-Key": {
Secrets: []config.Secret{"secret-key"},
},
},
},
}
client, err := config.NewClientFromConfig(cfg, "headers-client")
if err != nil {
panic(err)
}
// All requests include custom headers
}package main
import (
"github.com/prometheus/common/config"
)
const yamlConfig = `
basic_auth:
username: admin
password: secret123
tls_config:
ca_file: /etc/ssl/ca.pem
insecure_skip_verify: false
follow_redirects: true
enable_http2: true
`
func main() {
cfg, err := config.LoadHTTPConfig(yamlConfig)
if err != nil {
panic(err)
}
client, err := config.NewClientFromConfig(*cfg, "yaml-client")
if err != nil {
panic(err)
}
// Use client...
}package main
import (
"time"
"github.com/prometheus/common/config"
)
func main() {
cfg := config.DefaultHTTPClientConfig
client, err := config.NewClientFromConfig(
cfg,
"custom-client",
config.WithUserAgent("MyApp/1.0"),
config.WithIdleConnTimeout(90*time.Second),
config.WithHTTP2Disabled(),
)
if err != nil {
panic(err)
}
// Client with custom options
}