or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

assets.mdconfig.mdexpfmt.mdhelpers-templates.mdindex.mdmodel.mdpromslog-flag.mdpromslog.mdroute.mdserver.mdversion.md
tile.json

config.mddocs/

Config Package

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

import "github.com/prometheus/common/config"

Overview

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.

Constants

const secretToken = "<secret>"

Token used to represent masked secrets in marshaled output.

Variables

var MarshalSecretValue = false

Controls 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]TLSVersion

Map of TLS version names to constants (e.g., "TLS10" -> tls.VersionTLS10).

Core Types

Secret

type Secret string

A secret string that is masked when marshaling to prevent accidental exposure in logs or configs.

Methods

func (s Secret) MarshalYAML() (interface{}, error)

Marshals as <secret> unless MarshalSecretValue is true.

func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals secret from YAML.

func (s Secret) MarshalJSON() ([]byte, error)

Marshals as <secret> unless MarshalSecretValue is true.

URL

type URL struct {
    *url.URL
}

URL wrapper with custom marshaling/unmarshaling and redaction support.

Methods

func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals URL from YAML.

func (u URL) MarshalYAML() (interface{}, error)

Marshals URL as YAML string.

func (u *URL) Redacted() string

Returns URL with password replaced by "xxxxx".

func (u *URL) UnmarshalJSON(data []byte) error

Unmarshals URL from JSON.

func (u URL) MarshalJSON() ([]byte, error)

Marshals URL as JSON string.

Authentication Types

BasicAuth

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.

Methods

func (a *BasicAuth) SetDirectory(dir string)

Joins relative file paths with dir.

func (a *BasicAuth) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals from YAML with validation.

Authorization

type Authorization struct {
    Type            string
    Credentials     Secret
    CredentialsFile string
    CredentialsRef  string
}

HTTP Authorization header configuration for Bearer and custom authentication schemes.

Methods

func (a *Authorization) SetDirectory(dir string)

Joins relative file paths with dir.

OAuth2

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.

Methods

func (o *OAuth2) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals from YAML.

func (o *OAuth2) UnmarshalJSON(data []byte) error

Unmarshals from JSON.

func (o *OAuth2) SetDirectory(dir string)

Joins relative file paths with dir.

TLS Configuration

TLSVersion

type TLSVersion uint16

TLS protocol version.

Methods

func (v *TLSVersion) UnmarshalYAML(unmarshal func(interface{}) error) error
func (v TLSVersion) MarshalYAML() (interface{}, error)
func (v *TLSVersion) UnmarshalJSON(data []byte) error
func (v TLSVersion) MarshalJSON() ([]byte, error)
func (v *TLSVersion) String() string

Returns string representation of TLS version.

TLSRoundTripperSettings

type TLSRoundTripperSettings struct {
    CA   SecretReader
    Cert SecretReader
    Key  SecretReader
}

Settings for TLS RoundTripper configuration including CA, certificate, and key readers.

TLSConfig

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.

Methods

func (c *TLSConfig) SetDirectory(dir string)

Joins relative file paths with dir.

func (c *TLSConfig) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals from YAML with validation.

func (c *TLSConfig) Validate() error

Validates the TLS configuration.

Proxy Configuration

ProxyHeader

type ProxyHeader map[string][]Secret

HTTP headers for proxy CONNECT requests.

Methods

func (h *ProxyHeader) HTTPHeader() http.Header

Converts to standard http.Header.

ProxyConfig

type ProxyConfig struct {
    ProxyURL            URL
    NoProxy             string
    ProxyFromEnvironment bool
    ProxyConnectHeader   ProxyHeader
}

HTTP proxy configuration with environment variable support.

Methods

func (c ProxyConfig) Validate() error

Validates 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.Header

Returns headers to send in CONNECT requests.

Headers Configuration

Header

type Header struct {
    Values  []string
    Secrets []Secret
    Files   []string
}

Single HTTP header with multiple value sources.

Methods

func (h *Header) SetDirectory(dir string)

Joins relative file paths with dir.

Headers

type Headers struct {
    Headers map[string]Header
}

Custom HTTP headers configuration.

Methods

func (h Headers) MarshalJSON() ([]byte, error)
func (h *Headers) SetDirectory(dir string)

Joins relative file paths with dir.

func (h *Headers) Validate() error

Validates header configuration.

HTTP Client Configuration

HTTPClientConfig

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.

Methods

func (c *HTTPClientConfig) SetDirectory(dir string)

Joins relative file paths with dir.

func (c *HTTPClientConfig) Validate() error

Validates the configuration.

func (c *HTTPClientConfig) UnmarshalYAML(unmarshal func(interface{}) error) error

Unmarshals from YAML.

func (c *HTTPClientConfig) UnmarshalJSON(data []byte) error

Unmarshals from JSON.

func (c HTTPClientConfig) String() string

Returns string representation.

Secret Management

SecretReader Interface

type SecretReader interface {
    Fetch(ctx context.Context) (string, error)
    Description() string
    Immutable() bool
}

Interface for reading secrets from various sources.

SecretManager Interface

type SecretManager interface {
    Fetch(ctx context.Context, secretRef string) (string, error)
}

Interface for fetching secrets from external sources.

DirectorySetter Interface

type DirectorySetter interface {
    SetDirectory(dir string)
}

Interface for types that support setting a base directory for relative paths.

HTTP Client Functions

LoadHTTPConfig

func LoadHTTPConfig(s string) (*HTTPClientConfig, error)

Parses YAML string into HTTPClientConfig.

Parameters:

  • s - YAML configuration string

Returns: (*HTTPClientConfig, error)

LoadHTTPConfigFile

func LoadHTTPConfigFile(filename string) (*HTTPClientConfig, []byte, error)

Parses YAML file into HTTPClientConfig.

Parameters:

  • filename - Path to YAML configuration file

Returns: (*HTTPClientConfig, []byte, error) - Config, raw bytes, error

NewClientFromConfig

func NewClientFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HTTPClientOption) (*http.Client, error)

Creates a new HTTP client from configuration.

Parameters:

  • cfg - HTTP client configuration
  • name - Name for the client (used in User-Agent)
  • optFuncs - Optional configuration functions

Returns: (*http.Client, error)

NewRoundTripperFromConfig

func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HTTPClientOption) (http.RoundTripper, error)

Creates a new RoundTripper from configuration.

Parameters:

  • cfg - HTTP client configuration
  • name - Name for the client
  • optFuncs - Optional configuration functions

Returns: (http.RoundTripper, error)

NewRoundTripperFromConfigWithContext

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 operation
  • cfg - HTTP client configuration
  • name - Name for the client
  • optFuncs - Optional configuration functions

Returns: (http.RoundTripper, error)

TLS Functions

NewTLSConfig

func NewTLSConfig(cfg *TLSConfig, optFuncs ...TLSConfigOption) (*tls.Config, error)

Creates a new TLS configuration.

Parameters:

  • cfg - TLS configuration
  • optFuncs - Optional configuration functions

Returns: (*tls.Config, error)

NewTLSConfigWithContext

func NewTLSConfigWithContext(ctx context.Context, cfg *TLSConfig, optFuncs ...TLSConfigOption) (*tls.Config, error)

Creates a new TLS configuration with context.

Parameters:

  • ctx - Context for the operation
  • cfg - TLS configuration
  • optFuncs - Optional configuration functions

Returns: (*tls.Config, error)

NewTLSRoundTripper

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 configuration
  • settings - RoundTripper settings
  • newRT - Function to create the underlying RoundTripper

Returns: (http.RoundTripper, error)

NewTLSRoundTripperWithContext

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 operation
  • cfg - TLS configuration
  • settings - RoundTripper settings
  • newRT - Function to create the underlying RoundTripper

Returns: (http.RoundTripper, error)

RoundTripper Functions

NewHeadersRoundTripper

func NewHeadersRoundTripper(config *Headers, next http.RoundTripper) http.RoundTripper

Creates a RoundTripper that adds custom headers to requests.

Parameters:

  • config - Headers configuration
  • next - Next RoundTripper in chain

Returns: http.RoundTripper

NewAuthorizationCredentialsRoundTripper

func NewAuthorizationCredentialsRoundTripper(authType string, authCredentials SecretReader, rt http.RoundTripper) http.RoundTripper

Creates a RoundTripper with Authorization header.

Parameters:

  • authType - Authorization type (e.g., "Bearer")
  • authCredentials - Credentials reader
  • rt - Next RoundTripper in chain

Returns: http.RoundTripper

NewBasicAuthRoundTripper

func NewBasicAuthRoundTripper(username, password SecretReader, rt http.RoundTripper) http.RoundTripper

Creates a RoundTripper with Basic authentication.

Parameters:

  • username - Username reader
  • password - Password reader
  • rt - Next RoundTripper in chain

Returns: http.RoundTripper

NewOAuth2RoundTripper

func NewOAuth2RoundTripper(oauthCredential SecretReader, config *OAuth2, next http.RoundTripper, opts *httpClientOptions) http.RoundTripper

Creates a RoundTripper with OAuth2 authentication.

Parameters:

  • oauthCredential - OAuth credential reader
  • config - OAuth2 configuration
  • next - Next RoundTripper in chain
  • opts - HTTP client options

Returns: http.RoundTripper

NewUserAgentRoundTripper

func NewUserAgentRoundTripper(userAgent string, rt http.RoundTripper) http.RoundTripper

Creates a RoundTripper that sets User-Agent header.

Parameters:

  • userAgent - User-Agent string
  • rt - Next RoundTripper in chain

Returns: http.RoundTripper

NewHostRoundTripper

func NewHostRoundTripper(host string, rt http.RoundTripper) http.RoundTripper

Creates a RoundTripper that overrides the Host header.

Parameters:

  • host - Host header value
  • rt - Next RoundTripper in chain

Returns: http.RoundTripper

Secret Functions

NewInlineSecret

func NewInlineSecret(text string) *InlineSecret

Creates a new inline secret.

Parameters:

  • text - Secret text

Returns: *InlineSecret

NewFileSecret

func NewFileSecret(file string) *FileSecret

Creates a new file-based secret.

Parameters:

  • file - Path to secret file

Returns: *FileSecret

InlineSecret Type

type InlineSecret struct {
    // contains filtered or unexported fields
}

Inline secret implementation that stores secret text in memory.

Methods

func (s *InlineSecret) Fetch(ctx context.Context) (string, error)

Returns the inline secret text.

func (s *InlineSecret) Description() string

Returns "inline" as the description.

func (s *InlineSecret) Immutable() bool

Returns true since inline secrets are immutable.

FileSecret Type

type FileSecret struct {
    // contains filtered or unexported fields
}

File-based secret implementation that reads secret from a file.

Methods

func (s *FileSecret) Fetch(ctx context.Context) (string, error)

Reads and returns the secret from the file.

func (s *FileSecret) Description() string

Returns "file <path>" as the description.

func (s *FileSecret) Immutable() bool

Returns false since file secrets can change.

Utility Functions

JoinDir

func JoinDir(dir, path string) string

Joins dir and path if path is relative; returns path unchanged if absolute.

Parameters:

  • dir - Base directory
  • path - Path to join

Returns: Joined path

HTTP Client Options

Option Functions

func WithDialContextFunc(fn DialContextFunc) HTTPClientOption

Sets custom dial context function.

func WithNewTLSConfigFunc(newTLSConfigFunc NewTLSConfigFunc) HTTPClientOption

Sets custom TLS config creation function.

func WithKeepAlivesDisabled() HTTPClientOption

Disables HTTP keep-alives.

func WithHTTP2Disabled() HTTPClientOption

Disables HTTP/2.

func WithIdleConnTimeout(timeout time.Duration) HTTPClientOption

Sets idle connection timeout.

func WithUserAgent(ua string) HTTPClientOption

Sets User-Agent header.

func WithHost(host string) HTTPClientOption

Sets Host header.

func WithSecretManager(manager SecretManager) SecretManagerOption

Sets secret manager for fetching secrets from external sources.

Type Aliases

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.

OAuth2 JWT Grant Type

JwtGrantTypeConfig

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.

Methods

func (c *JwtGrantTypeConfig) TokenSource(ctx context.Context) oauth2.TokenSource

Returns an OAuth2 token source.

func (c *JwtGrantTypeConfig) Client(ctx context.Context) *http.Client

Returns a configured HTTP client.

Usage Examples

Basic 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))
}

TLS Configuration

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...
}

Basic Authentication

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...
}

Bearer Token

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
}

OAuth2 Configuration

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
}

Proxy Configuration

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
}

Custom Headers

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
}

Loading from YAML

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...
}

With Options

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
}