exhttp

package module
v0.0.0-...-938d389 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 24, 2026 License: Apache-2.0 Imports: 30 Imported by: 7

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTTPErrorFromResponse

func HTTPErrorFromResponse(res *http.Response) error

HTTPErrorFromResponse creates an error from the HTTP response.

func NewTLSTransport

func NewTLSTransport(
	baseTransport http.RoundTripper,
	tlsConfig *TLSConfig,
	logger *slog.Logger,
) (*http.Transport, error)

NewTLSTransport creates a new HTTP transport with TLS configuration.

func NewTelemetryTransport

func NewTelemetryTransport(transport http.RoundTripper, config TelemetryConfig) http.RoundTripper

NewTelemetryTransport creates a new transport with telemetry.

func ParseHttpURL

func ParseHttpURL(input string) (*url.URL, error)

ParseHttpURL parses and validate the input string to have http(s) scheme.

func ParsePort

func ParsePort(rawPort string, scheme string) (int, error)

ParsePort parses the server port from a raw string.

Types

type Client

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

Client is an http client wrapper with retry and implement the http client interface.

func NewClient

func NewClient(doer Doer, middlewares ...Middleware) *Client

NewClient creates a new client instance.

func (*Client) Do

func (r *Client) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

func (*Client) Get

func (r *Client) Get(url string) (*http.Response, error)

Get issues a GET to the specified URL.

func (*Client) Post

func (r *Client) Post(url string, bodyType string, body io.Reader) (*http.Response, error)

Post issues a POST to the specified URL.

type DialerConfig

type DialerConfig struct {
	// The maximum amount of time a dial will wait for a connect to complete.
	// If Deadline is also set, it may fail earlier.
	Timeout *model.Duration `` /* 172-byte string literal not displayed */
	// Keep-alive probes are enabled by default.
	KeepAliveEnabled *bool `json:"keepAliveEnabled,omitempty" mapstructure:"keepAliveEnabled" yaml:"keepAliveEnabled"`
	// The time between keep-alive probes. If zero, a default value of 15 seconds is used.
	KeepAliveInterval *model.Duration `` /* 202-byte string literal not displayed */
	// The maximum number of keep-alive probes that can go unanswered before dropping a connection.
	// If zero, a default value of 9 is used.
	KeepAliveCount *uint `json:"keepAliveCount,omitempty" jsonschema:"nullable,min=0" mapstructure:"keepAliveCount" yaml:"keepAliveCount"`
	// The time that the connection must be idle before the first keep-alive probe is sent.
	// If zero, a default value of 15 seconds is used.
	KeepAliveIdle *model.Duration `` /* 190-byte string literal not displayed */
}

DialerConfig contains options the http.Dialer to connect to an address.

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer abstracts an HTTP client interface.

type HTTPError

type HTTPError struct {
	StatusCode int         `json:"statusCode"`
	Headers    http.Header `json:"headers"`
	Body       []byte      `json:"body"`
}

HTTPError represents an error from HTTP response.

func (HTTPError) Error

func (he HTTPError) Error() string

Error implements the error interface.

type HTTPTransportConfig

type HTTPTransportConfig struct {
	// Options the http.Dialer to connect to an address
	Dialer *DialerConfig `json:"dialer,omitempty" mapstructure:"dialer" yaml:"dialer"`
	// The maximum amount of time an idle (keep-alive) connection will remain idle before closing itself. Zero means no limit.
	IdleConnTimeout *model.Duration `` /* 196-byte string literal not displayed */
	// If non-zero, specifies the amount of time to wait for a server's response headers after fully writing the request (including its body, if any).
	// This time does not include the time to read the response body.
	// This timeout is used to cover cases where the tcp connection works but the server never answers.
	ResponseHeaderTimeout *model.Duration `` /* 214-byte string literal not displayed */
	// The maximum amount of time to wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout *model.Duration `` /* 208-byte string literal not displayed */
	// If non-zero, specifies the amount of time to wait for a server's first response headers after fully writing the request headers if the request has an "Expect: 100-continue" header.
	ExpectContinueTimeout *model.Duration `` /* 214-byte string literal not displayed */
	// MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts. Zero means no limit.
	MaxIdleConns *int `json:"maxIdleConns,omitempty" mapstructure:"maxIdleConns" yaml:"maxIdleConns" jsonschema:"nullable,min=0"`
	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle (keep-alive) connections to keep per-host.
	MaxIdleConnsPerHost *int `` /* 126-byte string literal not displayed */
	// Optionally limits the total number of connections per host, including connections in the dialing, active, and idle states.
	// On limit violation, dials will block. Zero means no limit.
	MaxConnsPerHost *int `json:"maxConnsPerHost,omitempty" mapstructure:"maxConnsPerHost" yaml:"maxConnsPerHost" jsonschema:"nullable,min=0"`
	// Specifies a limit on how many response bytes are allowed in the server's response header.
	// Zero means to use a default limit.
	MaxResponseHeaderBytes *int64 `` /* 135-byte string literal not displayed */
	// ReadBufferSize specifies the size of the read buffer used when reading from the transport.
	// If zero, a default (currently 4KB) is used.
	ReadBufferSize *int `json:"readBufferSize,omitempty" mapstructure:"readBufferSize" yaml:"readBufferSize" jsonschema:"nullable,min=0"`
	// WriteBufferSize specifies the size of the write buffer used when writing to the transport.
	// If zero, a default (currently 4KB) is used.
	WriteBufferSize *int `json:"writeBufferSize,omitempty" mapstructure:"writeBufferSize" yaml:"writeBufferSize" jsonschema:"nullable,min=0"`
}

HTTPTransportConfig stores the http.Transport configuration for the http client.

func (HTTPTransportConfig) ToTransport

func (ttc HTTPTransportConfig) ToTransport() *http.Transport

ToTransport creates an http transport from the configuration.

type HTTPTransportTLSConfig

type HTTPTransportTLSConfig struct {
	HTTPTransportConfig

	TLS *TLSConfig `json:"tls,omitempty" jsonschema:"nullable" mapstructure:"tls" yaml:"tls"`
}

HTTPTransportTLSConfig stores the http.Transport configuration for the http client with TLS.

func (HTTPTransportTLSConfig) ToTransport

func (hc HTTPTransportTLSConfig) ToTransport(logger *slog.Logger) (*http.Transport, error)

ToTransport creates an http transport from the configuration with TLS.

type Middleware

type Middleware func(doer Doer) Doer

Middleware abstracts a function to create Doer.

func NewRetryMiddleware

func NewRetryMiddleware(config RetryPolicy) Middleware

func NewTelemetryMiddleware

func NewTelemetryMiddleware(config TelemetryConfig) Middleware

NewTelemetryMiddleware creates a new transport with telemetry.

type RetryPolicy

type RetryPolicy struct {
	// Number of retry times. Defaults to 0 (no retry).
	Times uint `json:"times,omitempty" mapstructure:"times" yaml:"times,omitempty"`
	// Delay retry delay in milliseconds. Defaults to 1 second
	Delay uint `json:"delay,omitempty" mapstructure:"delay" yaml:"delay,omitempty"`
	// HTTPStatus retries if the remote service returns one of these http status
	HTTPStatus []int `json:"httpStatus,omitempty" mapstructure:"httpStatus" yaml:"httpStatus,omitempty"`
	// How much does the reconnection time vary relative to the base value.
	// This is useful to prevent multiple clients to reconnect at the exact
	// same time, as it makes the wait times distinct.
	// Must be in range (0, 1); Defaults to 0.5.
	Jitter *float64 `json:"jitter,omitempty" mapstructure:"jitter" yaml:"jitter,omitempty"`
	// How much should the reconnection time grow on subsequent attempts.
	// Must be >=1; 1 = constant interval. Defaults to 1.5.
	Multiplier float64 `json:"multiplier,omitempty" mapstructure:"multiplier" yaml:"multiplier,omitempty"`
	// How much can the wait time grow.
	// If <=0 = the wait time can infinitely grow. Defaults to 60 seconds.
	MaxIntervalSeconds uint `json:"maxIntervalSeconds,omitempty" mapstructure:"maxIntervalSeconds" yaml:"maxIntervalSeconds,omitempty"`
	// Maximum total time in seconds for all retries.
	MaxElapsedTimeSeconds uint `json:"maxElapsedTimeSeconds,omitempty" mapstructure:"maxElapsedTimeSeconds" yaml:"maxElapsedTimeSeconds,omitempty"`
}

RetryPolicy represents the retry policy of request.

func (RetryPolicy) GetExponentialBackoff

func (rp RetryPolicy) GetExponentialBackoff() *backoff.ExponentialBackOff

GetExponentialBackoff returns a new GetExponentialBackoff config.

func (RetryPolicy) GetMaxElapsedTime

func (rp RetryPolicy) GetMaxElapsedTime() time.Duration

GetMaxElapsedTime returns the max elapsed time duration.

func (RetryPolicy) GetRetryHTTPStatus

func (rp RetryPolicy) GetRetryHTTPStatus() []int

GetRetryHTTPStatus returns the http status to be retried.

func (RetryPolicy) Schema

func (rp RetryPolicy) Schema() schema.ObjectType

Schema returns the object type schema of this type.

type RetryPolicySetting

type RetryPolicySetting struct {
	// Number of retry times
	Times *goenvconf.EnvInt `json:"times,omitempty" mapstructure:"times" yaml:"times,omitempty"`
	// The initial wait time in milliseconds before a retry is attempted.
	// Must be >0. Defaults to 1 second.
	Delay *goenvconf.EnvInt `json:"delay,omitempty" mapstructure:"delay" yaml:"delay,omitempty"`
	// HTTPStatus retries if the remote service returns one of these http status
	HTTPStatus []int `json:"httpStatus,omitempty" mapstructure:"httpStatus" yaml:"httpStatus,omitempty"`

	// How much does the reconnection time vary relative to the base value.
	// This is useful to prevent multiple clients to reconnect at the exact
	// same time, as it makes the wait times distinct.
	// Must be in range (0, 1); Defaults to 0.5.
	Jitter *float64 `json:"jitter,omitempty" jsonschema:"nullable,min=0,max=1" mapstructure:"jitter" yaml:"jitter,omitempty"`
	// How much should the reconnection time grow on subsequent attempts.
	// Must be >=1; 1 = constant interval. Defaults to 1.5.
	Multiplier float64 `json:"multiplier,omitempty" jsonschema:"min=1" mapstructure:"multiplier" yaml:"multiplier,omitempty"`
	// How much can the wait time in seconds grow. Defaults to 60 seconds.
	MaxIntervalSeconds uint `` /* 133-byte string literal not displayed */
	// Maximum total time in seconds for all retries.
	MaxElapsedTimeSeconds uint `` /* 142-byte string literal not displayed */
}

RetryPolicySetting represents retry policy settings.

func (RetryPolicySetting) Validate

func (rs RetryPolicySetting) Validate() (*RetryPolicy, error)

Validate if the current instance is valid.

type TLSConfig

type TLSConfig struct {
	// Path to the TLS cert to use for TLS required connections.
	CertFile *goenvconf.EnvString `json:"certFile,omitempty" mapstructure:"certFile" yaml:"certFile,omitempty"`
	// Alternative to cert_file. Provide the certificate contents as a base64-encoded string instead of a filepath.
	CertPem *goenvconf.EnvString `json:"certPem,omitempty" mapstructure:"certPem" yaml:"certPem,omitempty"`
	// Path to the TLS key to use for TLS required connections.
	KeyFile *goenvconf.EnvString `json:"keyFile,omitempty" mapstructure:"keyFile" yaml:"keyFile,omitempty"`
	// Alternative to key_file. Provide the key contents as a base64-encoded string instead of a filepath.
	KeyPem *goenvconf.EnvString `json:"keyPem,omitempty" mapstructure:"keyPem" yaml:"keyPem,omitempty"`
	// Path to the CA cert. For a client this verifies the server certificate. For a server this verifies client certificates.
	// If empty uses system root CA.
	CAFile *goenvconf.EnvString `json:"caFile,omitempty" mapstructure:"caFile" yaml:"caFile,omitempty"`
	// Alternative to ca_file. Provide the CA cert contents as a base64-encoded string instead of a filepath.
	CAPem *goenvconf.EnvString `json:"caPem,omitempty" mapstructure:"caPem" yaml:"caPem,omitempty"`
	// Additionally you can configure TLS to be enabled but skip verifying the server's certificate chain.
	InsecureSkipVerify *goenvconf.EnvBool `json:"insecureSkipVerify,omitempty" mapstructure:"insecureSkipVerify" yaml:"insecureSkipVerify,omitempty"`
	// Whether to load the system certificate authorities pool alongside the certificate authority.
	IncludeSystemCACertsPool *goenvconf.EnvBool `json:"includeSystemCACertsPool,omitempty" mapstructure:"includeSystemCACertsPool" yaml:"includeSystemCACertsPool,omitempty"`
	// Minimum acceptable TLS version.
	MinVersion string `json:"minVersion,omitempty" mapstructure:"minVersion" yaml:"minVersion,omitempty"`
	// Maximum acceptable TLS version.
	MaxVersion string `json:"maxVersion,omitempty" mapstructure:"maxVersion" yaml:"maxVersion,omitempty"`
	// Explicit cipher suites can be set. If left blank, a safe default list is used.
	// See https://go.dev/src/crypto/tls/cipher_suites.go for a list of supported cipher suites.
	CipherSuites []string `json:"cipherSuites,omitempty" mapstructure:"cipherSuites" yaml:"cipherSuites,omitempty"`
	// ServerName requested by client for virtual hosting.
	// This sets the ServerName in the TLSConfig. Please refer to
	// https://godoc.org/crypto/tls#Config for more information. (optional)
	ServerName *goenvconf.EnvString `json:"serverName,omitempty" mapstructure:"serverName" yaml:"serverName,omitempty"`
}

TLSConfig represents the transport layer security (LTS) configuration for the mutualTLS authentication.

func (TLSConfig) GetMaxVersion

func (tc TLSConfig) GetMaxVersion() (uint16, error)

GetMaxVersion parses the max TLS version from string.

func (TLSConfig) GetMinVersion

func (tc TLSConfig) GetMinVersion() (uint16, error)

GetMinVersion parses the minx TLS version from string.

func (TLSConfig) Validate

func (tc TLSConfig) Validate() error

Validate if the current instance is valid.

type TelemetryConfig

type TelemetryConfig struct {
	Tracer                     trace.Tracer
	Logger                     *slog.Logger
	Propagator                 propagation.TextMapPropagator
	Port                       int
	Attributes                 []attribute.KeyValue
	DisableHighCardinalityPath bool
}

TelemetryConfig hold optional options for the telemetry round tripper.

func (*TelemetryConfig) Validate

func (tc *TelemetryConfig) Validate()

Validate applies default values.

type TelemetryMiddleware

type TelemetryMiddleware struct {
	TelemetryConfig
	// contains filtered or unexported fields
}

TelemetryMiddleware wraps the client with logging and tracing.

func (TelemetryMiddleware) Do

Do wraps the base Doer with telemetry.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL