engine

package
v1.3.8 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearPools added in v1.3.8

func ClearPools()

ClearPools clears all sync.Pool instances used by the transport package. This is primarily useful for testing and debugging to ensure a clean state. Note: sync.Pool is automatically managed by the GC, so this is typically not needed in production code. The pools will be repopulated on next use.

func ClearRequestPools added in v1.3.8

func ClearRequestPools()

ClearRequestPools clears all sync.Pool instances used by the request package. This is primarily useful for testing and debugging to ensure a clean state. Note: sync.Pool is automatically managed by the GC, so this is typically not needed in production code. The pools will be repopulated on next use.

func ClearResponsePools added in v1.3.8

func ClearResponsePools()

ClearResponsePools clears all sync.Pool instances used by the response package. This is primarily useful for testing and debugging to ensure a clean state. Note: sync.Pool is automatically managed by the GC, so this is typically not needed in production code. The pools will be repopulated on next use.

func ClearURLCache added in v1.3.8

func ClearURLCache()

ClearURLCache clears the global URL cache to release memory. This is useful for long-running applications that want to free memory when the URL patterns change or during low-activity periods. Thread-safe: can be called concurrently with cache operations.

func GetURLCacheSize added in v1.3.8

func GetURLCacheSize() int

GetURLCacheSize returns the current number of entries in the URL cache. Useful for monitoring cache usage in production environments.

Types

type Client

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

func NewClient

func NewClient(config *Config, opts ...ClientOption) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) Delete

func (c *Client) Delete(url string, options ...RequestOption) (*Response, error)

func (*Client) Get

func (c *Client) Get(url string, options ...RequestOption) (*Response, error)

func (*Client) GetHealthStatus added in v1.1.0

func (c *Client) GetHealthStatus() HealthStatus

GetHealthStatus returns the current health status of the client.

func (*Client) Head

func (c *Client) Head(url string, options ...RequestOption) (*Response, error)

func (*Client) IsHealthy added in v1.1.0

func (c *Client) IsHealthy() bool

IsHealthy returns true if the client is healthy (error rate < 10%).

func (*Client) Options

func (c *Client) Options(url string, options ...RequestOption) (*Response, error)

func (*Client) Patch

func (c *Client) Patch(url string, options ...RequestOption) (*Response, error)

func (*Client) Post

func (c *Client) Post(url string, options ...RequestOption) (*Response, error)

func (*Client) Put

func (c *Client) Put(url string, options ...RequestOption) (*Response, error)

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, url string, options ...RequestOption) (*Response, error)

type ClientError

type ClientError struct {
	Type       ErrorType
	Message    string
	Cause      error
	URL        string
	Method     string
	Attempts   int
	StatusCode int    // HTTP status code if applicable
	Host       string // Host for circuit breaker errors
}

func ClassifyError

func ClassifyError(err error, reqURL, method string, attempts int) *ClientError

func (*ClientError) Code

func (e *ClientError) Code() string

func (*ClientError) Error

func (e *ClientError) Error() string

func (*ClientError) IsRetryable

func (e *ClientError) IsRetryable() bool

func (*ClientError) Unwrap

func (e *ClientError) Unwrap() error

type ClientOption added in v1.3.8

type ClientOption func(*clientOptions)

ClientOption is a functional option for configuring the Client.

func WithTransport added in v1.3.8

func WithTransport(transport TransportManager) ClientOption

WithTransport sets a custom transport for the client. This is useful for testing with mock transports or for custom protocols.

type Config

type Config struct {
	Timeout               time.Duration
	DialTimeout           time.Duration
	KeepAlive             time.Duration
	TLSHandshakeTimeout   time.Duration
	ResponseHeaderTimeout time.Duration
	IdleConnTimeout       time.Duration
	MaxIdleConns          int
	MaxIdleConnsPerHost   int
	MaxConnsPerHost       int
	ProxyURL              string

	// System proxy configuration
	EnableSystemProxy bool // Automatically detect and use system proxy settings

	TLSConfig           *tls.Config
	MinTLSVersion       uint16
	MaxTLSVersion       uint16
	InsecureSkipVerify  bool
	MaxResponseBodySize int64
	ValidateURL         bool
	ValidateHeaders     bool
	AllowPrivateIPs     bool
	StrictContentLength bool

	MaxRetries    int
	RetryDelay    time.Duration
	MaxRetryDelay time.Duration
	BackoffFactor float64
	Jitter        bool

	// CustomRetryPolicy allows providing a custom retry policy implementation.
	// If set, it overrides the built-in retry logic.
	CustomRetryPolicy types.RetryPolicy

	UserAgent       string
	Headers         map[string]string
	FollowRedirects bool
	MaxRedirects    int
	EnableHTTP2     bool

	CookieJar     http.CookieJar
	EnableCookies bool

	// DNS configuration
	EnableDoH   bool
	DoHCacheTTL time.Duration

	// Redirect whitelist configuration
	RedirectWhitelist *security.DomainWhitelist

	// Certificate pinning
	CertificatePinner security.CertificatePinner
}

Config defines the HTTP client configuration. Config should be treated as immutable after creation.

type ErrorType

type ErrorType int
const (
	ErrorTypeUnknown ErrorType = iota
	ErrorTypeNetwork
	ErrorTypeTimeout
	ErrorTypeContextCanceled
	ErrorTypeResponseRead
	ErrorTypeTransport
	ErrorTypeRetryExhausted
	ErrorTypeTLS
	ErrorTypeCertificate
	ErrorTypeDNS
	ErrorTypeValidation
	ErrorTypeHTTP
)

type HealthStatus added in v1.2.0

type HealthStatus struct {
	Healthy            bool
	TotalRequests      int64
	SuccessfulRequests int64
	FailedRequests     int64
	AverageLatency     time.Duration
	ErrorRate          float64
}

HealthStatus represents basic health metrics for the client.

type Metrics added in v1.3.8

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

Metrics collects and tracks HTTP client performance metrics. All methods are safe for concurrent use.

func (*Metrics) GetHealthStatus added in v1.3.8

func (m *Metrics) GetHealthStatus() HealthStatus

GetHealthStatus returns the current health status of the client. A client is considered healthy if its error rate is below 10%.

func (*Metrics) IsHealthy added in v1.3.8

func (m *Metrics) IsHealthy() bool

IsHealthy returns true if the client is healthy (error rate < 10%).

func (*Metrics) RecordRequest added in v1.3.8

func (m *Metrics) RecordRequest(latencyNs int64, success bool)

RecordRequest records the result of a single request. It updates the request counters and rolling average latency.

func (*Metrics) Reset added in v1.3.8

func (m *Metrics) Reset()

Reset resets all metrics to zero.

func (*Metrics) Snapshot added in v1.3.8

func (m *Metrics) Snapshot() MetricsSnapshot

Snapshot returns a point-in-time copy of the current metrics.

type MetricsSnapshot added in v1.3.8

type MetricsSnapshot struct {
	TotalRequests      int64
	SuccessfulRequests int64
	FailedRequests     int64
	AverageLatency     time.Duration
}

MetricsSnapshot represents a point-in-time snapshot of client metrics.

type MockTransport added in v1.3.8

type MockTransport struct {
	Response  *http.Response
	Error     error
	Called    bool
	CallCount int
	Requests  []*http.Request

	// Redirect behavior
	RedirectChain []string
	// contains filtered or unexported fields
}

MockTransport is a mock implementation of TransportManager for testing. It allows controlling the response and error returned by RoundTrip.

func NewMockTransport added in v1.3.8

func NewMockTransport(statusCode int, body string) *MockTransport

NewMockTransport creates a new MockTransport with a predefined response.

func (*MockTransport) Close added in v1.3.8

func (m *MockTransport) Close() error

Close implements TransportManager.

func (*MockTransport) GetCallCount added in v1.3.8

func (m *MockTransport) GetCallCount() int

GetCallCount returns the number of times RoundTrip was called.

func (*MockTransport) GetLastRequest added in v1.3.8

func (m *MockTransport) GetLastRequest() *http.Request

GetLastRequest returns the last request made, or nil if none.

func (*MockTransport) GetRedirectChain added in v1.3.8

func (m *MockTransport) GetRedirectChain(ctx context.Context) []string

GetRedirectChain implements TransportManager.

func (*MockTransport) Reset added in v1.3.8

func (m *MockTransport) Reset()

Reset clears all recorded state.

func (*MockTransport) RoundTrip added in v1.3.8

func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements TransportManager.

func (*MockTransport) SetError added in v1.3.8

func (m *MockTransport) SetError(err error)

SetError sets the error to return for subsequent requests.

func (*MockTransport) SetRedirectPolicy added in v1.3.8

func (m *MockTransport) SetRedirectPolicy(ctx context.Context, followRedirects bool, maxRedirects int) context.Context

SetRedirectPolicy implements TransportManager.

func (*MockTransport) SetResponse added in v1.3.8

func (m *MockTransport) SetResponse(statusCode int, body string)

SetResponse sets the response to return for subsequent requests.

type Request

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

func (*Request) Body

func (r *Request) Body() any

func (*Request) Context

func (r *Request) Context() context.Context

func (*Request) Cookies

func (r *Request) Cookies() []http.Cookie

func (*Request) FollowRedirects added in v1.3.0

func (r *Request) FollowRedirects() *bool

func (*Request) Headers

func (r *Request) Headers() map[string]string

func (*Request) MaxRedirects added in v1.3.0

func (r *Request) MaxRedirects() *int

func (*Request) MaxRetries

func (r *Request) MaxRetries() int

func (*Request) Method

func (r *Request) Method() string

Accessors (implement RequestMutator)

func (*Request) OnRequest added in v1.3.8

func (r *Request) OnRequest() RequestCallback

Callback accessors

func (*Request) OnResponse added in v1.3.8

func (r *Request) OnResponse() ResponseCallback

func (*Request) QueryParams

func (r *Request) QueryParams() map[string]any

func (*Request) SetBody added in v1.3.8

func (r *Request) SetBody(v any)

func (*Request) SetContext added in v1.3.8

func (r *Request) SetContext(v context.Context)

func (*Request) SetCookies added in v1.3.8

func (r *Request) SetCookies(v []http.Cookie)

func (*Request) SetFollowRedirects added in v1.3.8

func (r *Request) SetFollowRedirects(v *bool)

func (*Request) SetHeader added in v1.3.8

func (r *Request) SetHeader(key, value string)

func (*Request) SetHeaders added in v1.3.8

func (r *Request) SetHeaders(v map[string]string)

func (*Request) SetMaxRedirects added in v1.3.8

func (r *Request) SetMaxRedirects(v *int)

func (*Request) SetMaxRetries added in v1.3.8

func (r *Request) SetMaxRetries(v int)

func (*Request) SetMethod added in v1.3.8

func (r *Request) SetMethod(v string)

Mutators

func (*Request) SetOnRequest added in v1.3.8

func (r *Request) SetOnRequest(cb RequestCallback)

func (*Request) SetOnResponse added in v1.3.8

func (r *Request) SetOnResponse(cb ResponseCallback)

func (*Request) SetQueryParams added in v1.3.8

func (r *Request) SetQueryParams(v map[string]any)

func (*Request) SetTimeout added in v1.3.8

func (r *Request) SetTimeout(v time.Duration)

func (*Request) SetURL added in v1.3.8

func (r *Request) SetURL(v string)

func (*Request) Timeout

func (r *Request) Timeout() time.Duration

func (*Request) URL

func (r *Request) URL() string

type RequestCallback added in v1.3.8

type RequestCallback func(req *Request) error

RequestCallback is a callback function invoked before a request is sent.

type RequestOption

type RequestOption func(*Request) error

type RequestProcessor

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

func NewRequestProcessor

func NewRequestProcessor(config *Config) *RequestProcessor

func (*RequestProcessor) Build

func (p *RequestProcessor) Build(req *Request) (*http.Request, error)

type Response

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

Response represents an HTTP response. Response objects are safe to read from multiple goroutines after they are returned.

func (*Response) Attempts

func (r *Response) Attempts() int

func (*Response) Body

func (r *Response) Body() string

func (*Response) ContentLength

func (r *Response) ContentLength() int64

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

func (*Response) Duration

func (r *Response) Duration() time.Duration

func (*Response) Headers

func (r *Response) Headers() http.Header

func (*Response) Proto

func (r *Response) Proto() string

func (*Response) RawBody

func (r *Response) RawBody() []byte

func (*Response) RedirectChain added in v1.3.0

func (r *Response) RedirectChain() []string

func (*Response) RedirectCount added in v1.3.0

func (r *Response) RedirectCount() int

func (*Response) RequestHeaders added in v1.3.0

func (r *Response) RequestHeaders() http.Header

func (*Response) RequestMethod added in v1.3.8

func (r *Response) RequestMethod() string

func (*Response) RequestURL added in v1.3.8

func (r *Response) RequestURL() string

func (*Response) SetAttempts added in v1.3.8

func (r *Response) SetAttempts(v int)

func (*Response) SetBody added in v1.3.8

func (r *Response) SetBody(v string)

func (*Response) SetContentLength added in v1.3.8

func (r *Response) SetContentLength(v int64)

func (*Response) SetCookies added in v1.3.8

func (r *Response) SetCookies(v []*http.Cookie)

func (*Response) SetDuration added in v1.3.8

func (r *Response) SetDuration(v time.Duration)

func (*Response) SetHeader added in v1.3.8

func (r *Response) SetHeader(key string, values ...string)

SetHeader sets a header with multiple values (implements ResponseMutator)

func (*Response) SetHeaders added in v1.3.8

func (r *Response) SetHeaders(v http.Header)

func (*Response) SetProto added in v1.3.8

func (r *Response) SetProto(v string)

func (*Response) SetRawBody added in v1.3.8

func (r *Response) SetRawBody(v []byte)

func (*Response) SetRedirectChain added in v1.3.8

func (r *Response) SetRedirectChain(v []string)

func (*Response) SetRedirectCount added in v1.3.8

func (r *Response) SetRedirectCount(v int)

func (*Response) SetRequestHeaders added in v1.3.8

func (r *Response) SetRequestHeaders(v http.Header)

func (*Response) SetRequestMethod added in v1.3.8

func (r *Response) SetRequestMethod(v string)

func (*Response) SetRequestURL added in v1.3.8

func (r *Response) SetRequestURL(v string)

func (*Response) SetStatus added in v1.3.8

func (r *Response) SetStatus(v string)

func (*Response) SetStatusCode added in v1.3.8

func (r *Response) SetStatusCode(v int)

Mutators (implement ResponseMutator)

func (*Response) Status

func (r *Response) Status() string

func (*Response) StatusCode

func (r *Response) StatusCode() int

Accessors (implement ResponseAccessor)

type ResponseCallback added in v1.3.8

type ResponseCallback func(resp *Response) error

ResponseCallback is a callback function invoked after a response is received.

type ResponseProcessor

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

func NewResponseProcessor

func NewResponseProcessor(config *Config) *ResponseProcessor

func (*ResponseProcessor) Process

func (p *ResponseProcessor) Process(httpResp *http.Response) (*Response, error)

type RetryEngine

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

func NewRetryEngine

func NewRetryEngine(config *Config) *RetryEngine

func (*RetryEngine) GetDelay

func (r *RetryEngine) GetDelay(attempt int) time.Duration

func (*RetryEngine) GetDelayWithResponse added in v1.1.0

func (r *RetryEngine) GetDelayWithResponse(attempt int, resp *Response) time.Duration

func (*RetryEngine) MaxRetries

func (r *RetryEngine) MaxRetries() int

func (*RetryEngine) ShouldRetry

func (r *RetryEngine) ShouldRetry(resp types.ResponseReader, err error, attempt int) bool

ShouldRetry implements types.RetryPolicy interface.

type RoundTripper added in v1.3.8

type RoundTripper interface {
	// RoundTrip executes a single HTTP transaction and returns a Response.
	// RoundTrip should not attempt to interpret the response.
	// RoundTrip must always close the body, including on errors.
	RoundTrip(req *http.Request) (*http.Response, error)
}

RoundTripper is an interface for executing HTTP requests. This abstraction allows injecting custom transport implementations for testing, custom protocols, or specialized networking requirements.

Implementations must be safe for concurrent use by multiple goroutines.

type Transport

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

Transport manages HTTP transport with comprehensive security and optimal performance

func NewTransport

func NewTransport(config *Config, pool *connection.PoolManager) (*Transport, error)

NewTransport creates a new transport manager with connection pool

func (*Transport) CleanupRedirectSettings added in v1.3.8

func (t *Transport) CleanupRedirectSettings(ctx context.Context)

CleanupRedirectSettings releases redirect settings back to the pool. This MUST be called after the request completes to prevent memory leaks. It safely handles nil or invalid contexts.

func (*Transport) Close

func (t *Transport) Close() error

Close closes the transport and cleans up resources

func (*Transport) GetRedirectChain added in v1.3.0

func (t *Transport) GetRedirectChain(ctx context.Context) []string

GetRedirectChain returns the redirect chain from the context

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes an HTTP round trip

func (*Transport) SetRedirectPolicy added in v1.3.0

func (t *Transport) SetRedirectPolicy(ctx context.Context, followRedirects bool, maxRedirects int) context.Context

SetRedirectPolicy updates the redirect policy for a specific request Returns a new context with the redirect settings.

type TransportManager added in v1.3.8

type TransportManager interface {
	RoundTripper

	// SetRedirectPolicy configures redirect behavior for a specific request.
	// Returns a new context with the redirect settings.
	SetRedirectPolicy(ctx context.Context, followRedirects bool, maxRedirects int) context.Context

	// GetRedirectChain returns the list of URLs followed during redirects.
	GetRedirectChain(ctx context.Context) []string

	// CleanupRedirectSettings releases redirect settings back to the pool.
	// This MUST be called after the request completes to prevent memory leaks.
	CleanupRedirectSettings(ctx context.Context)

	// Close releases resources held by the transport.
	Close() error
}

TransportManager extends RoundTripper with redirect and lifecycle management.

Jump to

Keyboard shortcuts

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