Documentation
¶
Index ¶
- func AppendQueryParams(existingQuery string, params map[string]any) string
- func ClearHeaderPools()
- func ClearPools()
- func ClearRequestPools()
- func ClearResponsePools()
- func ClearURLCache()
- func CloneHeader(src http.Header) http.Header
- func CopyHeader(dst, src http.Header)
- func EncodeQueryParams(params map[string]any) string
- func GetHeader() *http.Header
- func GetHeaderValues() *[]string
- func GetURLCacheSize() int
- func PutHeader(h *http.Header)
- func PutHeaderValues(v *[]string)
- type Client
- func (c *Client) Close() error
- func (c *Client) Delete(url string, options ...RequestOption) (*Response, error)
- func (c *Client) Get(url string, options ...RequestOption) (*Response, error)
- func (c *Client) GetHealthStatus() HealthStatus
- func (c *Client) Head(url string, options ...RequestOption) (*Response, error)
- func (c *Client) IsHealthy() bool
- func (c *Client) Options(url string, options ...RequestOption) (*Response, error)
- func (c *Client) Patch(url string, options ...RequestOption) (*Response, error)
- func (c *Client) Post(url string, options ...RequestOption) (*Response, error)
- func (c *Client) Put(url string, options ...RequestOption) (*Response, error)
- func (c *Client) Request(ctx context.Context, method, url string, options ...RequestOption) (*Response, error)
- type ClientError
- type ClientOption
- type Config
- type ErrorType
- type HealthStatus
- type Metrics
- type MetricsSnapshot
- type MockTransport
- func (m *MockTransport) Close() error
- func (m *MockTransport) GetCallCount() int
- func (m *MockTransport) GetLastRequest() *http.Request
- func (m *MockTransport) GetRedirectChain(ctx context.Context) []string
- func (m *MockTransport) Reset()
- func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error)
- func (m *MockTransport) SetError(err error)
- func (m *MockTransport) SetRedirectPolicy(ctx context.Context, followRedirects bool, maxRedirects int) context.Context
- func (m *MockTransport) SetResponse(statusCode int, body string)
- type Request
- func (r *Request) Body() any
- func (r *Request) Context() context.Context
- func (r *Request) Cookies() []http.Cookie
- func (r *Request) FollowRedirects() *bool
- func (r *Request) Headers() map[string]string
- func (r *Request) MaxRedirects() *int
- func (r *Request) MaxRetries() int
- func (r *Request) Method() string
- func (r *Request) OnRequest() RequestCallback
- func (r *Request) OnResponse() ResponseCallback
- func (r *Request) QueryParams() map[string]any
- func (r *Request) SetBody(v any)
- func (r *Request) SetContext(v context.Context)
- func (r *Request) SetCookies(v []http.Cookie)
- func (r *Request) SetFollowRedirects(v *bool)
- func (r *Request) SetHeader(key, value string)
- func (r *Request) SetHeaders(v map[string]string)
- func (r *Request) SetMaxRedirects(v *int)
- func (r *Request) SetMaxRetries(v int)
- func (r *Request) SetMethod(v string)
- func (r *Request) SetOnRequest(cb RequestCallback)
- func (r *Request) SetOnResponse(cb ResponseCallback)
- func (r *Request) SetQueryParams(v map[string]any)
- func (r *Request) SetTimeout(v time.Duration)
- func (r *Request) SetURL(v string)
- func (r *Request) Timeout() time.Duration
- func (r *Request) URL() string
- type RequestCallback
- type RequestOption
- type RequestProcessor
- type Response
- func (r *Response) Attempts() int
- func (r *Response) Body() string
- func (r *Response) ContentLength() int64
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Duration() time.Duration
- func (r *Response) Headers() http.Header
- func (r *Response) Proto() string
- func (r *Response) RawBody() []byte
- func (r *Response) RedirectChain() []string
- func (r *Response) RedirectCount() int
- func (r *Response) RequestHeaders() http.Header
- func (r *Response) RequestMethod() string
- func (r *Response) RequestURL() string
- func (r *Response) SetAttempts(v int)
- func (r *Response) SetBody(v string)
- func (r *Response) SetContentLength(v int64)
- func (r *Response) SetCookies(v []*http.Cookie)
- func (r *Response) SetDuration(v time.Duration)
- func (r *Response) SetHeader(key string, values ...string)
- func (r *Response) SetHeaders(v http.Header)
- func (r *Response) SetProto(v string)
- func (r *Response) SetRawBody(v []byte)
- func (r *Response) SetRedirectChain(v []string)
- func (r *Response) SetRedirectCount(v int)
- func (r *Response) SetRequestHeaders(v http.Header)
- func (r *Response) SetRequestMethod(v string)
- func (r *Response) SetRequestURL(v string)
- func (r *Response) SetStatus(v string)
- func (r *Response) SetStatusCode(v int)
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- type ResponseCallback
- type ResponseProcessor
- type RetryEngine
- type RoundTripper
- type Transport
- type TransportManager
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendQueryParams ¶ added in v1.3.9
AppendQueryParams appends query parameters to an existing raw query string. This is more efficient than creating url.Values when you have an existing query.
func ClearHeaderPools ¶ added in v1.3.9
func ClearHeaderPools()
ClearHeaderPools clears all sync.Pool instances used for header operations. This is primarily useful for testing and debugging.
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 CloneHeader ¶ added in v1.3.9
CloneHeader creates a deep copy of headers using batch allocation. Returns a newly allocated header map that can be safely modified. SECURITY: Always allocates new slices to prevent data leakage between requests. The header map itself uses pooled allocation, but values are always copied. OPTIMIZATION: Uses batch allocation to reduce N allocations (one per header) to 1 allocation.
func CopyHeader ¶ added in v1.3.9
CopyHeader efficiently copies headers from src to dst using batch allocation. SECURITY: Allocates new slices for values because dst may hold long-term references. Using pooled slices here would cause memory leaks as the pool expects objects to be returned. OPTIMIZATION: Uses batch allocation to reduce N allocations (one per header) to 1 allocation.
func EncodeQueryParams ¶ added in v1.3.9
EncodeQueryParams efficiently encodes query parameters without allocating url.Values. This avoids the intermediate map allocation and uses pooled strings.Builder. Returns an empty string if params is nil or empty.
func GetHeader ¶ added in v1.3.9
GetHeader retrieves an http.Header from the pool. The returned header is cleared and ready for use.
func GetHeaderValues ¶ added in v1.3.9
func GetHeaderValues() *[]string
GetHeaderValues retrieves a string slice from the pool for header values.
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.
func PutHeader ¶ added in v1.3.9
PutHeader returns an http.Header to the pool. Headers with too many entries are discarded to prevent memory bloat. SECURITY: Always clears all header values to prevent sensitive data leakage, regardless of whether the header is pooled or discarded.
func PutHeaderValues ¶ added in v1.3.9
func PutHeaderValues(v *[]string)
PutHeaderValues returns a string slice to the pool.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) Delete ¶
func (c *Client) Delete(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
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)
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
IsRetryable determines if the error is retryable based on its type and cause.
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.
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 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
IsHealthy returns true if the client is healthy (error rate < 10%).
func (*Metrics) RecordRequest ¶ added in v1.3.8
RecordRequest records the result of a single request. It updates the request counters and rolling average latency.
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) 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) FollowRedirects ¶ added in v1.3.0
func (*Request) MaxRedirects ¶ added in v1.3.0
func (*Request) MaxRetries ¶
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 (*Request) SetContext ¶ added in v1.3.8
func (*Request) SetCookies ¶ added in v1.3.8
func (*Request) SetFollowRedirects ¶ added in v1.3.8
func (*Request) SetHeaders ¶ added in v1.3.8
func (*Request) SetMaxRedirects ¶ added in v1.3.8
func (*Request) SetMaxRetries ¶ added in v1.3.8
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 (*Request) SetTimeout ¶ added in v1.3.8
type RequestCallback ¶ added in v1.3.8
RequestCallback is a callback function invoked before a request is sent.
type RequestOption ¶
type RequestProcessor ¶
type RequestProcessor struct {
// contains filtered or unexported fields
}
func NewRequestProcessor ¶
func NewRequestProcessor(config *Config) *RequestProcessor
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) ContentLength ¶
func (*Response) RedirectChain ¶ added in v1.3.0
func (*Response) RedirectCount ¶ added in v1.3.0
func (*Response) RequestHeaders ¶ added in v1.3.0
func (*Response) RequestMethod ¶ added in v1.3.8
func (*Response) RequestURL ¶ added in v1.3.8
func (*Response) SetAttempts ¶ added in v1.3.8
func (*Response) SetContentLength ¶ added in v1.3.8
func (*Response) SetCookies ¶ added in v1.3.8
func (*Response) SetDuration ¶ added in v1.3.8
func (*Response) SetHeader ¶ added in v1.3.8
SetHeader sets a header with multiple values (implements ResponseMutator)
func (*Response) SetHeaders ¶ added in v1.3.8
func (*Response) SetRawBody ¶ added in v1.3.8
func (*Response) SetRedirectChain ¶ added in v1.3.8
func (*Response) SetRedirectCount ¶ added in v1.3.8
func (*Response) SetRequestHeaders ¶ added in v1.3.8
func (*Response) SetRequestMethod ¶ added in v1.3.8
func (*Response) SetRequestURL ¶ added in v1.3.8
func (*Response) SetStatusCode ¶ added in v1.3.8
Mutators (implement ResponseMutator)
func (*Response) StatusCode ¶
Accessors (implement ResponseAccessor)
type ResponseCallback ¶ added in v1.3.8
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
type RetryEngine ¶
type RetryEngine struct {
// contains filtered or unexported fields
}
func NewRetryEngine ¶
func NewRetryEngine(config *Config) *RetryEngine
func (*RetryEngine) GetDelayWithResponse ¶ added in v1.1.0
func (r *RetryEngine) GetDelayWithResponse(attempt int, resp *Response) time.Duration
GetDelayWithResponse returns the delay for the given attempt, considering response headers. It first checks for Retry-After header, then falls back to exponential backoff.
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) GetRedirectChain ¶ added in v1.3.0
GetRedirectChain returns the redirect chain from the context
func (*Transport) SetRedirectPolicy ¶ added in v1.3.0
func (t *Transport) SetRedirectPolicy(ctx context.Context, followRedirects bool, maxRedirects int) (context.Context, func())
SetRedirectPolicy updates the redirect policy for a specific request. Returns a new context with the redirect settings and a cleanup function.
IMPORTANT: The returned cleanup function MUST be called after the request completes to return settings to the pool. Use defer to ensure cleanup:
ctx, cleanup := transport.SetRedirectPolicy(ctx, true, 5) defer cleanup()
SECURITY: Failure to call cleanup will cause memory leaks and pool exhaustion.
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 and a cleanup function.
// The cleanup function MUST be called (typically via defer) after the request
// completes to prevent memory leaks from pool exhaustion.
SetRedirectPolicy(ctx context.Context, followRedirects bool, maxRedirects int) (context.Context, func())
// GetRedirectChain returns the list of URLs followed during redirects.
GetRedirectChain(ctx context.Context) []string
// Close releases resources held by the transport.
Close() error
}
TransportManager extends RoundTripper with redirect and lifecycle management.