Documentation
¶
Overview ¶
Package engine implements the core HTTP client engine with request processing, response handling, connection pooling, retry logic, and middleware support.
Index ¶
- Variables
- func AppendQueryEscape(b appendStringWriter, s string)
- func ApplyOptions(req *Request, options []RequestOption) error
- func CloneHeader(src http.Header) http.Header
- func FormatQueryParam(v any) string
- func ReleaseRequest(req *Request)
- func ReleaseResponse(r *Response)
- type Client
- type ClientError
- type Config
- type ErrorType
- type Request
- func (r *Request) AllowPrivateIPs() *bool
- func (r *Request) Apply(src *Request)
- func (r *Request) Body() any
- func (r *Request) Context() context.Context
- func (r *Request) Cookies() []http.Cookie
- func (r *Request) EnsureQueryParams() map[string]any
- 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) NoTimeout() bool
- func (r *Request) OnRequest() requestCallback
- func (r *Request) OnRequestMutator() func(types.RequestMutator) error
- func (r *Request) OnResponse() responseCallback
- func (r *Request) OnResponseMutator() func(types.ResponseMutator) error
- func (r *Request) QueryParams() map[string]any
- func (r *Request) RetryNonIdempotent() *bool
- func (r *Request) SanitizedURL() string
- func (r *Request) SetAllowPrivateIPs(v *bool)
- 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) SetNoTimeout(v bool)
- func (r *Request) SetOnRequest(cb requestCallback)
- func (r *Request) SetOnRequestMutator(cb func(types.RequestMutator) error)
- func (r *Request) SetOnResponse(cb responseCallback)
- func (r *Request) SetOnResponseMutator(cb func(types.ResponseMutator) error)
- func (r *Request) SetQueryParams(v map[string]any)
- func (r *Request) SetRetryNonIdempotent(v *bool)
- func (r *Request) SetSanitizedURL(v string)
- func (r *Request) SetStreamBody(v bool)
- func (r *Request) SetTimeout(v time.Duration)
- func (r *Request) SetURL(v string)
- func (r *Request) StreamBody() bool
- func (r *Request) Timeout() time.Duration
- func (r *Request) URL() string
- type RequestOption
- 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) ProxyURL() string
- func (r *Response) RawBody() []byte
- func (r *Response) RawBodyReader() io.ReadCloser
- 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) SetProxyURL(v string)
- func (r *Response) SetRawBody(v []byte)
- func (r *Response) SetRawBodyReader(rc io.ReadCloser)
- 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
- func (r *Response) TransferHeaders() http.Header
- func (r *Response) TransferRequestHeaders() http.Header
Constants ¶
This section is empty.
Variables ¶
var ErrClientClosed = errors.New("client is closed")
ErrClientClosed is returned when attempting to use a closed client.
Functions ¶
func AppendQueryEscape ¶ added in v1.6.0
func AppendQueryEscape(b appendStringWriter, s string)
AppendQueryEscape appends the URL-query-escaped form of s directly to b. Writing straight into the writer avoids the intermediate escaped string allocation that b.WriteString(QueryEscape(s)) would incur whenever s contains characters that need escaping. Inputs with no escapable bytes are written verbatim after a single scan. Uses the RFC 3986 unreserved set — note this differs from url.QueryEscape for the space character (%20 here, '+' in the stdlib form encoding), which servers decode identically. Very large inputs fall back to the standard library.
func ApplyOptions ¶ added in v1.7.0
func ApplyOptions(req *Request, options []RequestOption) error
ApplyOptions runs a list of options against a concrete *Request. The concrete type is what the engine pools and passes onward; RequestOption's interface parameter lets external options stay decoupled from it.
Exported (rather than unexported) because the httpc facade applies options to its own pooled *Request before running the middleware chain — see clientImpl.executeRequest.
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. OPTIMIZATION: Uses batch allocation to reduce N allocations (one per header) to 1 allocation. For single-value headers (the common case), uses a shared backing array to reduce slice header overhead.
func FormatQueryParam ¶ added in v1.4.0
FormatQueryParam converts a value to string for query parameters. Optimized to avoid fmt.Sprintf allocations for common types.
MAINTENANCE: this type switch has two siblings that MUST stay in sync — writeQueryParamValue (pools.go, writes the wire format) and the facade's queryValueLength (public_options.go, measures length without allocating). query_param_parity_test.go guards the drift; when adding a type, add it to all three.
func ReleaseRequest ¶ added in v1.5.0
func ReleaseRequest(req *Request)
ReleaseRequest returns a Request to the shared pool after clearing all fields. Resets maxRetries to maxRetriesUnset so recycled requests inherit the client's retry config.
func ReleaseResponse ¶ added in v1.4.0
func ReleaseResponse(r *Response)
ReleaseResponse returns a Response to the pool for reuse. Call this when the Response data has been consumed and copied elsewhere. After calling this, the Response must not be used.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the internal HTTP client that manages requests, responses, retries, and connection pooling.
func NewClient ¶
NewClient creates a new engine Client with the given configuration and optional client options.
func (*Client) Close ¶
Close releases the client's resources, including the connection pool and transport. It is safe to call multiple times; subsequent calls are no-ops. Returns any error encountered while closing sub-components.
func (*Client) Request ¶
func (c *Client) Request(ctx context.Context, method, url string, options ...RequestOption) (*Response, error)
Request executes an HTTP request with the given method, URL, and options. It acquires a pooled Request, applies the options, processes it through the transport layer with retry support, and returns the resulting Response. Returns ErrClientClosed if the client has been closed.
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
// ProxyURL is the URL of the proxy that was selected for the final attempt
// of this request — the same transport-recorded source that populates
// RequestMeta.ProxyURL on success (Result.Meta.ProxyURL). The transport's
// Proxy callback runs before dialing, so even proxy dial failures carry
// the proxy that was about to be used. Populated on errors returned from
// Client request methods when a proxy (a single Connection.ProxyURL or a
// proxy pool entry) is configured; empty for direct connections, for
// errors raised before dispatch (validation, callback failures), and
// under EnableSystemProxy (dynamic detection is not recorded, mirroring
// RequestMeta.ProxyURL). Redacted form (proxy password masked), safe to
// log. With rotation each retry attempt may use a different proxy; this
// field reports the last attempt's proxy.
ProxyURL string
// contains filtered or unexported fields
}
ClientError represents a classified HTTP client error with context about the failed request.
func (*ClientError) Code ¶
func (e *ClientError) Code() string
Code returns a short string code identifying the error type (e.g., "NETWORK_ERROR", "TIMEOUT").
func (*ClientError) Error ¶
func (e *ClientError) Error() string
Error implements the error interface. It formats the error as "METHOD url: message" (with credentials redacted from the URL) followed by the cause and attempt count when present.
func (*ClientError) IsRetryable ¶
func (e *ClientError) IsRetryable() bool
IsRetryable determines if the error is retryable based on its type and cause.
Scope: this consults the built-in retry classification only (error type, cause, and the built-in retryable HTTP status table). The retry ENGINE additionally honors Connection.ExtraRetryableStatusCodes, so for a status code configured there, the engine may retry a request whose ClientError reports IsRetryable() == false. Treat this method as "retryable under the default policy", not as a prediction of the engine's behavior for custom status codes.
func (*ClientError) Unwrap ¶
func (e *ClientError) Unwrap() error
Unwrap returns the underlying cause error, supporting errors.Is and errors.As.
type Config ¶
type Config struct {
// Connection carries the transport, TLS, proxy, cookie-jar, and connection-
// pool configuration. convertToEngineConfig initializes it from
// connection.DefaultConfig() and overrides the shared fields, so the
// connection-only fields (MaxTotalConns, ExpectContinueTimeout,
// DisableKeepAlives, ForceAttemptHTTP2) keep their defaults with no
// engine-side merge.
Connection connection.Config
// Timeout is the overall request timeout, applied at the engine level as
// the total budget across retries.
Timeout time.Duration
// ProxyRotatePerRequest closes idle connections before each request so the
// transport re-evaluates the proxy pool. It is engine-only (not a
// connection.Config field): rotation is an engine/retry concern, not a
// transport setting.
ProxyRotatePerRequest bool
// TLSFingerprint enables full-stack browser transport fingerprinting. The
// fingerprint adapter replaces the transport, so this is engine-only.
TLSFingerprint string
// TLSFingerprintDisableSessionTickets forces a full TLS handshake on
// every fingerprinted connection (see the public SecurityConfig field).
TLSFingerprintDisableSessionTickets bool
MaxResponseBodySize int64
MaxRequestBodySize int64
MaxDecompressedBodySize int64
ValidateURL bool
ValidateHeaders bool
StrictContentLength bool
MaxRetries int
RetryDelay time.Duration
MaxRetryDelay time.Duration
BackoffFactor float64
Jitter bool
// RetryNonIdempotent allows retrying non-idempotent methods (POST, PATCH,
// and custom methods). Default false: a timeout or retryable 5xx may
// arrive after the server already committed the operation, and replaying
// the buffered body would duplicate it (duplicate payment, double insert,
// ...). See the retry guard in executeWithRetry.
RetryNonIdempotent bool
// ExtraRetryableStatusCodes are HTTP status codes beyond the built-in set
// (408/429/500/502/503/504) that should trigger a retry. Seeded from
// Connection.ProxyRotateOnStatus to rotate proxies on status-based blocks.
ExtraRetryableStatusCodes []int
// 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
// EnableCookies enables automatic cookie handling; the jar itself lives on
// Connection.CookieJar.
EnableCookies bool
// Redirect whitelist configuration
RedirectWhitelist *security.DomainWhitelist
// SensitiveHeaders extends the built-in cross-origin redirect strip set
// (redirectSensitiveHeaders) with caller-declared credential headers, in
// canonical (http.CanonicalHeaderKey) form. Empty = built-ins only.
SensitiveHeaders []string
// Certificate pinning
CertificatePinner security.CertificatePinner
}
Config defines the HTTP client configuration. Config should be treated as immutable after creation.
Connection holds the transport and connection-pool settings; the engine adds request, security, and retry policy on top. Sharing one connection.Config value (rather than mirroring its fields here) removes the field-by-field copy that previously mapped engine.Config onto connection.Config by hand — see buildConnectionConfig and convertToEngineConfig.
type ErrorType ¶
type ErrorType int
ErrorType represents the classification of an HTTP client error.
const ( // ErrorTypeUnknown indicates an unknown or unclassified error. ErrorTypeUnknown ErrorType = iota // ErrorTypeNetwork indicates a network-level error. ErrorTypeNetwork // ErrorTypeTimeout indicates a timeout occurred during the request. ErrorTypeTimeout // ErrorTypeContextCanceled indicates the request context was canceled. ErrorTypeContextCanceled // ErrorTypeResponseRead indicates an error reading the response body. ErrorTypeResponseRead // ErrorTypeTransport indicates an HTTP transport-level error. ErrorTypeTransport // ErrorTypeRetryExhausted indicates all retry attempts have been exhausted. ErrorTypeRetryExhausted // ErrorTypeTLS indicates a TLS handshake or protocol error. ErrorTypeTLS // ErrorTypeCertificate indicates a certificate validation error. ErrorTypeCertificate // ErrorTypeDNS indicates a DNS resolution error. ErrorTypeDNS // ErrorTypeValidation indicates a request validation error. ErrorTypeValidation // ErrorTypeHTTP indicates an HTTP-level error (4xx, 5xx responses). ErrorTypeHTTP )
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request represents an HTTP request with method, URL, headers, body, and options.
The exported accessor and mutator methods below implement the types.RequestMutator interface (which embeds both read and write methods). They are trivial field pass-throughs and intentionally lack per-method godoc; refer to the interface definition for their contract.
func AcquireRequest ¶ added in v1.5.0
func AcquireRequest() *Request
AcquireRequest retrieves a Request from the shared pool. The caller must call ReleaseRequest when done.
func (*Request) AllowPrivateIPs ¶ added in v1.5.2
func (*Request) Apply ¶ added in v1.6.3
Apply transfers all per-request mutable state from src onto r. It exists so callers that forward a request through a fresh engine.Request call — e.g. the facade middleware chain's terminal handler — stay in sync with the Request type by construction instead of enumerating fields by hand.
Ownership: the pooled headers and query-parameter maps are MOVED, not copied — src's references are cleared so a later release of src cannot return the same maps to the pool twice. The context is not transferred: it is owned by the engine.Client.Request call that created r. Optional fields (followRedirects, maxRedirects, allowPrivateIPs, callbacks) are copied only when set on src, preserving r's defaults otherwise.
func (*Request) EnsureQueryParams ¶ added in v1.5.0
func (*Request) FollowRedirects ¶ added in v1.3.0
func (*Request) Headers ¶
Headers returns the internal pooled headers map. Keys are stored in canonical (http.CanonicalHeaderKey) form — see SetHeader. The reference is valid only for the lifetime of this request: after the request is released the map is cleared and recycled for other requests. Callers that need to retain the data (async logging, audit) must copy it.
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) OnRequestMutator ¶ added in v1.7.0
func (r *Request) OnRequestMutator() func(types.RequestMutator) error
OnRequestMutator returns the pre-request callback as a func(types.RequestMutator) error. The field stores the concrete requestCallback type whose underlying representation is func(*Request) error; the two named func types differ, so the concrete callback is adapted by wrapping (a *Request is a types.RequestMutator) rather than converted.
func (*Request) OnResponse ¶ added in v1.3.8
func (r *Request) OnResponse() responseCallback
func (*Request) OnResponseMutator ¶ added in v1.7.0
func (r *Request) OnResponseMutator() func(types.ResponseMutator) error
OnResponseMutator returns the post-response callback as a func(types.ResponseMutator) error (see OnRequestMutator for the adaptation note).
func (*Request) QueryParams ¶
QueryParams returns the internal pooled query-parameter map, subject to the same lifetime contract as Headers — copy before retaining.
func (*Request) RetryNonIdempotent ¶ added in v1.6.3
func (*Request) SanitizedURL ¶ added in v1.5.0
func (*Request) SetAllowPrivateIPs ¶ added in v1.5.2
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) SetHeader ¶ added in v1.3.8
SetHeader stores a single header, canonicalizing the key via http.CanonicalHeaderKey. The same header set under multiple casings ("Cache-Control" and "cache-control") therefore collapses onto one canonical entry with the last write winning deterministically, matching http.Header.Set semantics; previously the two raw keys coexisted in the map and the build-time canonicalizer let Go's random iteration order pick the winner. CanonicalHeaderKey leaves keys it cannot canonicalize (set directly by middleware, which bypasses option validation) unchanged, so such keys behave exactly as before.
func (*Request) SetHeaders ¶ added in v1.3.8
SetHeaders replaces all headers with a COPY of v held in a pooled map, canonicalizing each key (see SetHeader). Keys are visited in sorted order so that when v holds one header under multiple casings (e.g. "Cache-Control" and "cache-control"), the later key in sort order deterministically wins — not Go's randomized map iteration order.
SECURITY (pool poisoning): Request objects are pooled, and resetRequest returns whatever map is stored here to the shared headersMapPool (after clearing it). Storing a caller-owned map by reference would hand that map to an unrelated future request — concurrent map writes, or request A's headers appearing in request B. User middleware reaches this method via the RequestMutator interface, so the setter must copy. Internal zero-copy moves of engine-owned pooled maps use moveHeaders (see Apply).
func (*Request) SetMaxRedirects ¶ added in v1.3.8
func (*Request) SetMaxRetries ¶ added in v1.3.8
func (*Request) SetNoTimeout ¶ added in v1.6.3
func (*Request) SetOnRequest ¶ added in v1.3.8
func (r *Request) SetOnRequest(cb requestCallback)
func (*Request) SetOnRequestMutator ¶ added in v1.7.0
func (r *Request) SetOnRequestMutator(cb func(types.RequestMutator) error)
SetOnRequestMutator stores a pre-request callback supplied as func(types.RequestMutator) error, adapting it to the concrete requestCallback type the field stores (which the engine invokes with a *Request). The type assertion narrows the interface parameter back to the concrete request the engine always passes. These two methods are the sole bridge the types.RequestCallbackSetter contract needs: the public facade installs callbacks through this interface-facing pair so it never names *engine.Request.
func (*Request) SetOnResponse ¶ added in v1.3.8
func (r *Request) SetOnResponse(cb responseCallback)
func (*Request) SetOnResponseMutator ¶ added in v1.7.0
func (r *Request) SetOnResponseMutator(cb func(types.ResponseMutator) error)
SetOnResponseMutator stores a post-response callback supplied as func(types.ResponseMutator) error (see SetOnRequestMutator).
func (*Request) SetQueryParams ¶ added in v1.3.8
SetQueryParams replaces all query parameters with a COPY of v held in a pooled map. See SetHeaders for why copying is mandatory (pool poisoning).
func (*Request) SetRetryNonIdempotent ¶ added in v1.6.3
func (*Request) SetSanitizedURL ¶ added in v1.5.0
func (*Request) SetStreamBody ¶ added in v1.4.0
func (*Request) SetTimeout ¶ added in v1.3.8
func (*Request) StreamBody ¶ added in v1.4.0
type RequestOption ¶
type RequestOption func(types.RequestMutator) error
RequestOption is a function that modifies a pooled *Request before it is sent. It takes types.RequestMutator (rather than the concrete *Request) so options compose through the same abstraction as middleware. The facade's public RequestOption is an interface; the facade adapts it to this func type at the boundary (see httpc.toEngineOptions), so the engine's option-application loop stays a plain function call. Built-in facade options that need engine-specific fields reach them via a type assertion on the concrete *Request.
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.
The exported accessor and mutator methods below implement the types.ResponseMutator interface (which embeds ResponseReader and write methods). They are trivial field pass-throughs and intentionally lack per-method godoc; refer to the interface definition for their contract.
func (*Response) ContentLength ¶
func (*Response) RawBody ¶
RawBody returns the raw response body bytes. Read-locked so a concurrent SetRawBody (e.g. from another middleware goroutine) cannot race with this read — mirroring the locking discipline of Body and SetRawBody.
func (*Response) RawBodyReader ¶ added in v1.4.0
func (r *Response) RawBodyReader() io.ReadCloser
RawBodyReader returns the streaming-mode body reader. Read-locked for the same reason as RawBody: SetRawBodyReader writes the field under bodyMu.
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) SetProxyURL ¶ added in v1.6.3
func (*Response) SetRawBody ¶ added in v1.3.8
func (*Response) SetRawBodyReader ¶ added in v1.4.1
func (r *Response) SetRawBodyReader(rc io.ReadCloser)
SetRawBodyReader replaces the raw body reader. Passing nil transfers ownership away from the response so that ReleaseResponse will not close it.
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)
func (*Response) TransferHeaders ¶ added in v1.5.0
TransferHeaders returns the response headers and clears the internal reference. The caller takes ownership of the returned map. Used by the public layer to avoid a redundant CloneHeader when converting engine.Response to Result.
func (*Response) TransferRequestHeaders ¶ added in v1.5.0
TransferRequestHeaders returns the request headers and clears the internal reference.