Documentation
¶
Overview ¶
Package httpc provides a high-performance HTTP client library with secure defaults.
Key Features ¶
- Secure by default with TLS 1.2+, CRLF injection prevention, header validation
- High performance with connection pooling, HTTP/2, and goroutine-safe operations
- Built-in resilience with smart retry and exponential backoff
- Clean API with simplified request options
Quick Start ¶
Basic usage with package-level functions:
result, err := httpc.Get("https://api.example.com/data")
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Body())
Two API Layers ¶
httpc offers two equivalent request paths, mirroring the net/http split between http.Get and http.Client:
- Package-level functions (httpc.Get, httpc.Post, ...) use a lazily initialized default client. Best for scripts and one-off requests.
- Client instance methods (client.Get, client.Post, ...) give full control over configuration, connection pooling, and lifecycle.
Both layers accept the same request options (WithHeader, WithJSON, ...) and return the same *Result type:
// Package-level — zero setup, shared default client
result, err := httpc.Get("https://api.example.com/data")
// Client instance — full control, explicit lifecycle
client, err := httpc.NewDefault()
defer func() { _ = client.Close() }()
result, err := client.Get("https://api.example.com/data")
Package-level functions are thin wrappers around a singleton client managed internally (see SetDefaultClient, CloseDefaultClient). For long-running services, prefer an explicit client instance so you control its configuration and lifetime.
Client Creation ¶
Create a client with default configuration:
client, err := httpc.NewDefault()
defer func() { _ = client.Close() }()
Create a client with custom configuration:
cfg := httpc.DefaultConfig() cfg.Timeouts.Request = 60 * time.Second cfg.Retry.MaxRetries = 5 client, err := httpc.New(cfg)
Use preset configurations:
client, err := httpc.New(httpc.SecureConfig()) // Security-focused client, err := httpc.New(httpc.PerformanceConfig()) // High-throughput client, err := httpc.New(httpc.TestingConfig()) // Testing only!
Configuration Conventions ¶
All httpc constructors follow the same pattern:
- Instance configuration uses Config structs, not functional options.
- Every Config struct has a Default*Config() function returning sensible defaults — start from it, then modify fields as needed.
- The main Config and SessionConfig are passed by value (required). Middleware configs are passed by pointer and may be nil to accept defaults; DownloadConfig is passed by pointer but is required (FilePath must be set).
Per-request modifiers (WithHeader, WithJSON, WithTimeout, ...) are functional options applied to individual requests. This is a separate concern from instance configuration: instance config lives in Config structs; per-request config lives in With* options.
// Main client: shortcut for defaults client, err := httpc.NewDefault() // Main client: Config by value (customized) cfg := httpc.DefaultConfig() cfg.Timeouts.Request = 60 * time.Second client, err := httpc.New(cfg) // Session manager: required SessionConfig (NewSessionManagerDefault() for defaults) sm, err := httpc.NewSessionManagerDefault() // Download: *DownloadConfig (required, must set FilePath) dcfg := httpc.DefaultDownloadConfig() dcfg.FilePath = "/path/to/file"
SSRF Protection ¶
By default, AllowPrivateIPs is false, blocking connections to private/reserved IP addresses (127.0.0.1, 10.x, 192.168.x, 169.254.x, etc.). This protects against Server-Side Request Forgery attacks.
Set AllowPrivateIPs to true only when connecting to internal services:
// Allow internal service access (VPNs, proxies, corporate networks) cfg := httpc.DefaultConfig() cfg.Security.AllowPrivateIPs = true client, err := httpc.New(cfg) // Or use the secure preset (SSRF protection already enabled) client, err := httpc.New(httpc.SecureConfig())
Request Options ¶
Core options:
// Headers
httpc.WithHeader("Authorization", "Bearer token")
httpc.WithHeaderMap(map[string]string{"X-Custom": "value"})
httpc.WithUserAgent("my-app/1.0")
// Body
httpc.WithJSON(data)
httpc.WithXML(data)
httpc.WithForm(map[string]string{"key": "value"})
httpc.WithFormData(multipartData)
httpc.WithFile("file", "document.pdf", fileBytes)
httpc.WithBody(rawData)
httpc.WithBinary(binaryData)
// Query parameters
httpc.WithQuery("page", 1)
httpc.WithQueryMap(map[string]any{"page": 1, "limit": 10})
// Authentication
httpc.WithBearerToken(token)
httpc.WithBasicAuth(username, password)
// Cookies
httpc.WithCookie(http.Cookie{Name: "session", Value: "abc"})
httpc.WithCookieString("session=abc; token=xyz")
httpc.WithCookieMap(map[string]string{"session": "abc"})
httpc.WithSecureCookie(securityConfig)
// Request control
httpc.WithContext(ctx)
httpc.WithTimeout(30 * time.Second)
httpc.WithMaxRetries(3)
httpc.WithFollowRedirects(false)
httpc.WithMaxRedirects(5)
httpc.WithStreamBody(true)
// Callbacks
httpc.WithOnRequest(callback)
httpc.WithOnResponse(callback)
DomainClient ¶
For session management across requests to the same domain:
dc, err := httpc.NewDomain("https://api.example.com", httpc.DefaultConfig())
defer dc.Close()
dc.SetHeader("Authorization", "Bearer "+token)
// Headers automatically included
result, err := dc.Request(ctx, "GET", "/users")
Context Handling ¶
Use context for timeout and cancellation:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := client.Request(ctx, "GET", "https://api.example.com/data")
Timeout Behavior ¶
By default, TimeoutConfig.ResponseHeader is 0 (disabled). The context-level timeout from Timeouts.Request (default 180s) or WithTimeout() is the sole mechanism controlling how long to wait for a response.
This design ensures WithTimeout() has full control over request duration, which is essential for AI APIs and long-polling endpoints that need extended response times:
// AI API that may take minutes to respond
result, err := httpc.Post(url,
httpc.WithJSON(payload),
httpc.WithTimeout(900*time.Second),
)
For security-critical applications, use SecureConfig() which sets a strict transport-level ResponseHeaderTimeout as defense-in-depth against slowloris attacks.
Request Defaults (RequestDefaults) ¶
Per-request defaults — User-Agent, default headers, redirect policy — live on Config.Defaults (RequestDefaults), populated by DefaultConfig():
cfg := httpc.DefaultConfig() cfg.Defaults.UserAgent = "myapp/2.0" cfg.Defaults.FollowRedirects = false cfg.Defaults.Headers["Authorization"] = "Bearer token" client, err := httpc.New(cfg)
Middleware Configuration ¶
Every configurable middleware follows the same pattern: a XxxConfig struct, a DefaultXxxConfig() constructor, and a XxxMiddleware(cfg) factory that accepts a nil config (selecting defaults). Start from the default, modify fields, then pass to the constructor:
mw := httpc.LoggingMiddleware(&httpc.LoggingConfig{
LogFunc: log.Printf,
})
mw := httpc.MetricsMiddleware(&httpc.MetricsConfig{
OnMetrics: func(method, url string, code int, d time.Duration, err error) { ... },
})
mw := httpc.RequestIDMiddleware(httpc.DefaultRequestIDConfig())
auditCfg := httpc.DefaultAuditConfig()
auditCfg.OnAudit = func(event httpc.AuditEvent) { ... }
mw := httpc.AuditMiddleware(auditCfg)
mw := httpc.TimeoutMiddleware(&httpc.TimeoutMiddlewareConfig{
Duration: 30 * time.Second,
})
mw := httpc.HeaderMiddleware(&httpc.HeaderConfig{
Headers: map[string]string{"X-Service": "api"},
})
For more information, see https://github.com/cybergodev/httpc
Index ¶
- Constants
- Variables
- func CloseDefaultClient() error
- func FormatBytes(bytes int64) string
- func FormatSpeed(bytesPerSecond float64) string
- func SetDefaultClient(client Client) error
- func SetSecurityWarnOutput(w io.Writer)
- func ValidateConfig(cfg *Config) error
- type AuditConfig
- type AuditEvent
- type BodyKind
- type CertificatePinner
- type ChecksumAlgorithm
- type Client
- type ClientError
- type Config
- type ConnectionConfig
- type CookieSecurityConfig
- type Doer
- type DomainClient
- func (dc *DomainClient) Close() error
- func (dc *DomainClient) Delete(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Domain() string
- func (dc *DomainClient) Download(ctx context.Context, path string, cfg *DownloadConfig, ...) (*DownloadResult, error)
- func (dc *DomainClient) Get(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Head(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Options(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Patch(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Post(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Put(path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Request(ctx context.Context, method, path string, options ...RequestOption) (*Result, error)
- func (dc *DomainClient) Session() *SessionManager
- func (dc *DomainClient) URL() string
- type DomainClienter
- type DownloadConfig
- type DownloadProgressCallback
- type DownloadResult
- type ErrorType
- type FileData
- type FormData
- type Handler
- type HeaderConfig
- type LoggingConfig
- type MetricsConfig
- type MiddlewareConfig
- type MiddlewareFunc
- func AuditMiddleware(config *AuditConfig) MiddlewareFunc
- func Chain(middlewares ...MiddlewareFunc) MiddlewareFunc
- func HeaderMiddleware(config *HeaderConfig) MiddlewareFunc
- func LoggingMiddleware(config *LoggingConfig) MiddlewareFunc
- func MetricsMiddleware(config *MetricsConfig) MiddlewareFunc
- func RecoveryMiddleware() MiddlewareFunc
- func RequestIDMiddleware(config *RequestIDConfig) MiddlewareFunc
- func TimeoutMiddleware(config *TimeoutMiddlewareConfig) MiddlewareFunc
- type ProxyStrategy
- type RequestDefaults
- type RequestIDConfig
- type RequestInfo
- type RequestMeta
- type RequestMutator
- type RequestOption
- func WithAllowPrivateIPs(allow bool) RequestOption
- func WithBasicAuth(username, password string) RequestOption
- func WithBearerToken(token string) RequestOption
- func WithBinary(data []byte, contentType ...string) RequestOption
- func WithBody(data any, kind ...BodyKind) RequestOption
- func WithContext(ctx context.Context) RequestOption
- func WithCookie(cookie http.Cookie) RequestOption
- func WithCookieMap(cookies map[string]string) RequestOption
- func WithCookieString(cookieString string) RequestOption
- func WithCookies(cookies []http.Cookie) RequestOption
- func WithFile(fieldName, filename string, content []byte) RequestOption
- func WithFollowRedirects(follow bool) RequestOption
- func WithForm(data map[string]string) RequestOption
- func WithFormData(data *FormData) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithHeaderMap(headers map[string]string) RequestOption
- func WithJSON(data any) RequestOption
- func WithMaxRedirects(maxRedirects int) RequestOption
- func WithMaxRetries(maxRetries int) RequestOption
- func WithOnRequest(callback func(req RequestMutator) error) RequestOption
- func WithOnResponse(callback func(resp ResponseMutator) error) RequestOption
- func WithQuery(key string, value any) RequestOption
- func WithQueryMap(params map[string]any) RequestOption
- func WithSecureCookie(securityConfig *CookieSecurityConfig) RequestOption
- func WithStreamBody(stream bool) RequestOption
- func WithTimeout(timeout time.Duration) RequestOption
- func WithUserAgent(userAgent string) RequestOption
- func WithXML(data any) RequestOption
- type ResponseInfo
- type ResponseMutator
- type Result
- func Delete(url string, options ...RequestOption) (*Result, error)
- func Get(url string, options ...RequestOption) (*Result, error)
- func Head(url string, options ...RequestOption) (*Result, error)
- func Options(url string, options ...RequestOption) (*Result, error)
- func Patch(url string, options ...RequestOption) (*Result, error)
- func Post(url string, options ...RequestOption) (*Result, error)
- func Put(url string, options ...RequestOption) (*Result, error)
- func Request(ctx context.Context, method, url string, options ...RequestOption) (*Result, error)
- func (r *Result) Body() string
- func (r *Result) GetCookie(name string) *http.Cookie
- func (r *Result) GetRequestCookie(name string) *http.Cookie
- func (r *Result) HasCookie(name string) bool
- func (r *Result) HasRequestCookie(name string) bool
- func (r *Result) IsClientError() bool
- func (r *Result) IsRedirect() bool
- func (r *Result) IsServerError() bool
- func (r *Result) IsSuccess() bool
- func (r *Result) Proto() string
- func (r *Result) RawBody() []byte
- func (r *Result) RequestCookies() []*http.Cookie
- func (r *Result) ResponseCookies() []*http.Cookie
- func (r *Result) SaveToFile(filePath string) error
- func (r *Result) StatusCode() int
- func (r *Result) String() string
- func (r *Result) Unmarshal(v any) error
- type RetryConfig
- type RetryPolicy
- type SecurityConfig
- type SessionConfig
- type SessionManager
- func (s *SessionManager) ClearCookies()
- func (s *SessionManager) ClearHeaders()
- func (s *SessionManager) DeleteCookie(name string)
- func (s *SessionManager) DeleteHeader(key string)
- func (s *SessionManager) GetCookie(name string) *http.Cookie
- func (s *SessionManager) GetCookies() []*http.Cookie
- func (s *SessionManager) GetHeaders() map[string]string
- func (s *SessionManager) SetCookie(cookie *http.Cookie) error
- func (s *SessionManager) SetCookieSecurity(config *CookieSecurityConfig)
- func (s *SessionManager) SetCookies(cookies []*http.Cookie) error
- func (s *SessionManager) SetHeader(key, value string) error
- func (s *SessionManager) SetHeaders(headers map[string]string) error
- func (s *SessionManager) UpdateFromCookies(cookies []*http.Cookie)
- func (s *SessionManager) UpdateFromResult(result *Result)
- type TimeoutConfig
- type TimeoutMiddlewareConfig
Constants ¶
const ( // SourceIPKey is the context key for source IP address in audit events. SourceIPKey auditContextKey = "source_ip" // UserIDKey is the context key for user identifier in audit events. UserIDKey auditContextKey = "user_id" )
const ( // ProxyStrategyRoundRobin cycles through proxies in order (default). // Each selection advances to the next proxy, so a retry naturally lands on // a different IP without any extra wiring. ProxyStrategyRoundRobin = proxypool.StrategyRoundRobin // ProxyStrategyRandom picks a healthy proxy uniformly at random. ProxyStrategyRandom = proxypool.StrategyRandom )
Variables ¶
var ( // ErrClientClosed is returned when attempting to use a closed client. // This occurs after calling Close() on a client instance. // Use errors.Is(err, httpc.ErrClientClosed) to detect this condition. ErrClientClosed = engine.ErrClientClosed // ErrNilConfig is returned when a nil configuration is provided. // Always provide a valid Config or use DefaultConfig(). ErrNilConfig = errors.New("config cannot be nil") // ErrInvalidHeader is returned when header validation fails. // Headers must not contain control characters or exceed size limits. ErrInvalidHeader = errors.New("invalid header") // ErrInvalidTimeout is returned when timeout is negative or exceeds limits. // Timeout must be between 0 and 30 minutes. ErrInvalidTimeout = errors.New("invalid timeout") // ErrInvalidRetry is returned when retry configuration is invalid. // MaxRetries must be 0-10, BackoffFactor must be 1.0-10.0. ErrInvalidRetry = errors.New("invalid retry configuration") // ErrInvalidConnection is returned when connection configuration is invalid. // MaxIdleConns and MaxConnsPerHost must be within allowed ranges. ErrInvalidConnection = errors.New("invalid connection configuration") // ErrInvalidSecurity is returned when security configuration is invalid. // MaxResponseBodySize and MaxDecompressedBodySize must be within allowed ranges. ErrInvalidSecurity = errors.New("invalid security configuration") // ErrInvalidMiddleware is returned when middleware configuration is invalid. // MaxRedirects must be 0-50, UserAgent must not exceed length limit. ErrInvalidMiddleware = errors.New("invalid middleware configuration") // ErrEmptyFilePath is returned when file path is empty. // Provide a valid file path for download operations. ErrEmptyFilePath = errors.New("file path cannot be empty") // ErrFileExists is returned when file already exists and Overwrite is false. // Set Overwrite=true or ResumeDownload=true in DownloadConfig. ErrFileExists = errors.New("file already exists") // ErrResponseBodyEmpty is returned when attempting to parse empty response body. // Check response.RawBody before calling Unmarshal() or other parsing methods. ErrResponseBodyEmpty = errors.New("response body is empty") // ErrResponseBodyTooLarge is returned when response body exceeds size limit. // Increase MaxResponseBodySize in Config or reduce response size. ErrResponseBodyTooLarge = errors.New("response body too large") )
Functions ¶
func CloseDefaultClient ¶
func CloseDefaultClient() error
CloseDefaultClient closes the default client and resets it. After calling this, the next package-level function call will create a new client. This function is safe for concurrent use.
func FormatBytes ¶
FormatBytes formats a byte count as a human-readable string (e.g., "1.50 MB").
func FormatSpeed ¶
FormatSpeed formats a byte-per-second rate as a human-readable string (e.g., "1.50 MB/s").
func SetDefaultClient ¶
SetDefaultClient sets a custom client as the default for package-level functions. The previous default client is closed automatically. Only *clientImpl instances created by this package are supported. Returns an error if client is nil, not created by this package, or already closed.
func SetSecurityWarnOutput ¶ added in v1.5.0
SetSecurityWarnOutput redirects security warnings (e.g., TestingConfig, InsecureSkipVerify) to the specified writer. Pass io.Discard to suppress all warnings.
func ValidateConfig ¶ added in v1.1.0
ValidateConfig validates the configuration and returns an error if invalid. This is called internally by New() but can also be called explicitly.
Types ¶
type AuditConfig ¶ added in v1.6.0
type AuditConfig struct {
// OnAudit receives an AuditEvent for each completed request/response cycle.
// If nil, the middleware is a no-op.
OnAudit func(event AuditEvent)
// Format specifies the output format: "text" (default) or "json"
Format string
// IncludeHeaders includes request/response headers in the audit log
IncludeHeaders bool
// MaskHeaders is a list of header names to mask (e.g., "Authorization", "Cookie")
MaskHeaders []string
// SanitizeError removes sensitive information from error messages
SanitizeError bool
}
AuditConfig configures the audit middleware. Use DefaultAuditConfig() as the starting point.
func DefaultAuditConfig ¶ added in v1.6.0
func DefaultAuditConfig() *AuditConfig
DefaultAuditConfig returns an AuditConfig with default settings.
Format: "text" IncludeHeaders: false MaskHeaders: sensitive header names (Authorization, Cookie, etc.) SanitizeError: true
type AuditEvent ¶ added in v1.3.8
type AuditEvent struct {
Timestamp time.Time `json:"timestamp"`
Method string `json:"method"`
URL string `json:"url"` // Sanitized (credentials removed)
StatusCode int `json:"statusCode"`
Duration time.Duration `json:"duration"`
Attempts int `json:"attempts"`
Error error `json:"error,omitempty"`
SourceIP string `json:"sourceIP,omitempty"`
UserID string `json:"userID,omitempty"`
RedirectChain []string `json:"redirectChain,omitempty"`
ReqHeaders map[string][]string `json:"reqHeaders,omitempty"`
RespHeaders map[string][]string `json:"respHeaders,omitempty"`
}
AuditEvent represents a security audit event for high-security scenarios. It captures request/response details for compliance logging in financial, medical, and government applications.
func (AuditEvent) MarshalJSON ¶ added in v1.3.8
func (e AuditEvent) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for AuditEvent. It handles the error field specially to avoid exposing sensitive error details.
type BodyKind ¶ added in v1.3.9
type BodyKind int
BodyKind represents the type of request body for WithBody.
const ( // BodyAuto auto-detects body type based on input data. // Auto-detection rules: // - string → text/plain // - []byte → application/octet-stream // - map[string]string → application/x-www-form-urlencoded // - *FormData → multipart/form-data // - io.Reader → passed through (no Content-Type set) // - other types → application/json BodyAuto BodyKind = iota // BodyJSON forces JSON encoding regardless of input type. BodyJSON // BodyXML forces XML encoding regardless of input type. BodyXML // BodyForm forces application/x-www-form-urlencoded encoding. // Input must be map[string]string or compatible type. BodyForm // BodyBinary forces binary/octet-stream encoding. // Input must be []byte or string. BodyBinary // BodyMultipart forces multipart/form-data encoding. // Input must be *FormData. BodyMultipart )
type CertificatePinner ¶ added in v1.5.2
type CertificatePinner = security.CertificatePinner
CertificatePinner verifies that a server's certificate matches a known, expected certificate or public key. This is certificate pinning: it defends against man-in-the-middle attacks even if a trusted Certificate Authority is compromised, because the handshake is rejected unless the peer presents a pinned key.
This is a type alias for the internal security.CertificatePinner interface. Construct a pinner with NewSPKIHashPinner, NewPublicKeyPinner, or NewCertificatePinnerChain, then assign it to Config.Security.CertificatePinner:
pinner, err := httpc.NewSPKIHashPinner(
"YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2fuihg=", // current key
"C5+lpZ7tcVwmwQIMcRtPbsQtWLABXhQzejna0wHFr8M=", // backup key (rotation)
)
if err != nil {
log.Fatal(err)
}
cfg := httpc.DefaultConfig()
cfg.Security.CertificatePinner = pinner
client, err := httpc.New(cfg)
Advanced users may implement this interface directly to support custom pinning strategies (e.g. pinning full certificates instead of public keys).
func NewCertificatePinnerChain ¶ added in v1.5.2
func NewCertificatePinnerChain(pinners ...CertificatePinner) CertificatePinner
NewCertificatePinnerChain combines multiple pinners into one. A certificate is accepted if ANY of the wrapped pinners accepts it. Use this to support multiple pinning strategies simultaneously or to combine rotation keys built with different constructors.
Returns a no-op pinner (accepts nothing) when called with no pinners.
func NewPublicKeyPinner ¶ added in v1.5.2
func NewPublicKeyPinner(publicKeys ...[]byte) (CertificatePinner, error)
NewPublicKeyPinner creates a certificate pinner from one or more DER-encoded PKIX public keys (as returned by x509.MarshalPKIXPublicKey). The pinner hashes each key with SHA-256 internally; this is a convenience over NewSPKIHashPinner when you already hold the raw public key bytes.
Returns an error if no valid public key is provided.
func NewSPKIHashPinner ¶ added in v1.5.2
func NewSPKIHashPinner(hashes ...string) (CertificatePinner, error)
NewSPKIHashPinner creates a certificate pinner from one or more base64-encoded SHA-256 hashes of DER-encoded SubjectPublicKeyInfo (SPKI). This is the most common pinning format (used by HPKP) and is the recommended approach.
Supply multiple hashes to support key rotation: the handshake succeeds if the peer's key matches ANY pinned hash.
Generate a hash from a certificate with:
openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der \ | openssl dgst -sha256 -binary | openssl enc -base64
Returns an error if no valid hash is provided or if a hash is not valid base64.
type ChecksumAlgorithm ¶ added in v1.4.1
type ChecksumAlgorithm string
ChecksumAlgorithm specifies the hash algorithm for download integrity verification.
const ( // ChecksumSHA256 uses SHA-256 for integrity verification. ChecksumSHA256 ChecksumAlgorithm = "sha256" )
type Client ¶
type Client interface {
Doer
// Convenience methods for common HTTP verbs
Get(url string, options ...RequestOption) (*Result, error)
Post(url string, options ...RequestOption) (*Result, error)
Put(url string, options ...RequestOption) (*Result, error)
Patch(url string, options ...RequestOption) (*Result, error)
Delete(url string, options ...RequestOption) (*Result, error)
Head(url string, options ...RequestOption) (*Result, error)
Options(url string, options ...RequestOption) (*Result, error)
// Download downloads a file from url to the path specified in cfg.
// cfg must be non-nil and cfg.FilePath must be set (ErrEmptyFilePath otherwise).
// Use DefaultDownloadConfig() as the starting point, then set FilePath and any
// of ProgressCallback / Overwrite / ResumeDownload / Checksum as needed.
Download(ctx context.Context, url string, cfg *DownloadConfig, options ...RequestOption) (*DownloadResult, error)
// Close releases resources held by the client
Close() error
}
Client is the main interface for making HTTP requests. It extends Doer with convenience methods and lifecycle management.
func New ¶
New creates a new HTTP client with the given configuration. Pass DefaultConfig() for sensible defaults, or use a preset like SecureConfig().
Returns an error if the configuration fails validation (e.g., invalid Security.SSRFExemptCIDRs, mutually exclusive security settings) or if the underlying engine client cannot be created.
Examples:
// Use default configuration (or call NewDefault() for the same result) client, err := httpc.New(httpc.DefaultConfig()) // Use custom configuration cfg := httpc.DefaultConfig() cfg.Timeouts.Request = 60 * time.Second client, err := httpc.New(cfg) // Use preset configuration client, err := httpc.New(httpc.SecureConfig())
func NewDefault ¶ added in v1.6.0
NewDefault creates a new HTTP client with default configuration. It is a convenience shortcut for New(DefaultConfig()); see New for possible error conditions (default configuration is always valid, so this effectively never returns an error in practice).
Example:
client, err := httpc.NewDefault()
defer func() { _ = client.Close() }()
type ClientError ¶ added in v1.3.8
type ClientError = engine.ClientError
ClientError represents a classified HTTP client error with context. It provides detailed error information including error type, retryability, and request context.
Use errors.As to check for ClientError:
var clientErr *httpc.ClientError
if errors.As(err, &clientErr) {
fmt.Println(clientErr.Code())
fmt.Println(clientErr.IsRetryable())
}
type Config ¶
type Config struct {
Timeouts TimeoutConfig
Connection ConnectionConfig
Security SecurityConfig
Retry RetryConfig
Middleware MiddlewareConfig
Defaults RequestDefaults
// contains filtered or unexported fields
}
Config defines the HTTP client configuration organized into logical groups. Use DefaultConfig() for sensible defaults, or use preset configurations like SecureConfig(), PerformanceConfig(), or MinimalConfig().
Example:
cfg := httpc.DefaultConfig() cfg.Timeouts.Request = 60 * time.Second cfg.Retry.MaxRetries = 5 cfg.Connection.ProxyURL = "http://proxy:8080" client, err := httpc.New(cfg)
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults. The returned config is safe for modification.
SSRF Protection: AllowPrivateIPs defaults to false, blocking connections to private/reserved IPs (127.0.0.1, 10.x, 192.168.x, 169.254.x, etc.). Setting to true disables ALL SSRF protection including localhost checks — use SSRFExemptCIDRs for selective allowlisting.
func MinimalConfig ¶ added in v1.1.0
func MinimalConfig() Config
MinimalConfig returns a lightweight configuration with minimal features. Use this for simple, one-off requests where you don't need retries or advanced features.
func PerformanceConfig ¶ added in v1.1.0
func PerformanceConfig() Config
PerformanceConfig returns a configuration optimized for high-throughput scenarios. This config uses larger connection pools, longer timeouts, while maintaining essential security validations.
SECURITY NOTE: This configuration maintains URL and header validation for security. If you need to disable these for maximum performance in a trusted environment, manually set cfg.Security.ValidateURL = false and cfg.Security.ValidateHeaders = false, but be aware of the security implications (injection attacks, SSRF).
func SecureConfig ¶ added in v1.1.0
func SecureConfig() Config
SecureConfig returns a configuration optimized for security-critical applications. This config uses stricter timeouts, disables redirects, and has SSRF protection enabled.
Key security features:
- AllowPrivateIPs = false: Blocks connections to private/reserved IP addresses (SSRF protection)
- FollowRedirects = false: Prevents redirect-based SSRF attacks
- Stricter timeouts: Reduces window for slowloris attacks
- Smaller response limits: Prevents memory exhaustion
Use this preset when making requests to user-provided URLs or in security-sensitive contexts.
func TestingConfig ¶ added in v1.1.0
func TestingConfig() Config
TestingConfig returns a configuration optimized for testing environments. WARNING: This config disables security features and should NEVER be used in production. Use this ONLY for local development and testing with localhost/private networks.
SECURITY: This function will log a warning if called outside of a test environment. For production, use SecureConfig() or DefaultConfig() instead.
type ConnectionConfig ¶ added in v1.4.0
type ConnectionConfig struct {
// MaxIdleConns is the maximum number of idle connections across all hosts.
// Default: 50.
MaxIdleConns int
// MaxConnsPerHost is the maximum connections per host (idle + active).
// Default: 10.
MaxConnsPerHost int
// ProxyURL specifies an explicit proxy server URL (e.g., "http://proxy:8080").
// Takes precedence over EnableSystemProxy. Default: "" (no proxy).
ProxyURL string
// EnableSystemProxy enables automatic detection of system proxy settings.
// Default: false.
EnableSystemProxy bool
// ProxyPool specifies a list of proxy servers for rotation. When set,
// requests are distributed across the proxies using ProxyPoolStrategy.
// Connection failures (dial/TLS) to a proxy trigger passive circuit
// breaking: after ProxyFailureThreshold consecutive failures the proxy is
// temporarily removed from rotation and restored after ProxyCooldown.
//
// Priority: lower than ProxyURL, higher than EnableSystemProxy. If both
// ProxyURL and ProxyPool are set, ProxyURL wins (single-proxy mode).
// Default: nil (no proxy pool).
ProxyPool []string
// ProxyPoolStrategy selects how proxies are chosen from ProxyPool.
// Default: ProxyStrategyRoundRobin.
ProxyPoolStrategy ProxyStrategy
// ProxyFailureThreshold is the number of consecutive connection failures
// (dial/TLS) to a proxy before it is temporarily removed from rotation.
// Zero defaults to 3. HTTP status codes do NOT trigger this — use
// ProxyRotateOnStatus for status-based rotation.
ProxyFailureThreshold int
// ProxyCooldown is how long a circuit-broken proxy stays out of rotation
// before being retried (half-open probe). Zero defaults to 30s.
ProxyCooldown time.Duration
// ProxyRotateOnStatus specifies HTTP status codes that trigger a retry with
// a different proxy. When a response returns one of these codes and
// Retry.MaxRetries > 0, the request is retried; under round-robin or random
// strategy the retry naturally selects a different proxy IP.
//
// Typical use: []int{403} for CF/WAF IP-based blocking. Unlike
// connection failures, status-based rotation does NOT circuit-break the
// proxy — blocks are often target-specific (a proxy blocked on one site may
// work fine on another). Requires Retry.MaxRetries > 0 to take effect.
// Default: nil.
ProxyRotateOnStatus []int
// EnableHTTP2 enables HTTP/2 protocol support.
// Default: true.
EnableHTTP2 bool
// EnableCookies enables automatic cookie handling with a cookie jar.
// Default: false.
EnableCookies bool
// EnableDoH enables DNS-over-HTTPS for DNS resolution.
// Default: false.
EnableDoH bool
// DoHCacheTTL is the cache duration for DoH DNS responses.
// Default: 5 minutes.
DoHCacheTTL time.Duration
// MaxResponseHeaderBytes limits the maximum size of the server's response headers.
// This protects against malicious servers sending excessively large headers.
// Default: 0 (uses Go stdlib default of 10MB).
MaxResponseHeaderBytes int64
}
ConnectionConfig configures connection pooling and proxy behavior.
type CookieSecurityConfig ¶ added in v1.4.0
type CookieSecurityConfig = validation.CookieSecurityConfig
CookieSecurityConfig configures cookie security attribute validation. Use DefaultCookieSecurityConfig() or StrictCookieSecurityConfig() to create instances. Alias for validation.CookieSecurityConfig to avoid importing the internal package.
Example:
cfg := httpc.DefaultCookieSecurityConfig() cfg.RequireSecure = true config.Security.CookieSecurity = cfg
func DefaultCookieSecurityConfig ¶ added in v1.4.0
func DefaultCookieSecurityConfig() *CookieSecurityConfig
DefaultCookieSecurityConfig returns a CookieSecurityConfig with default settings. By default, no security attributes are required.
func StrictCookieSecurityConfig ¶ added in v1.4.0
func StrictCookieSecurityConfig() *CookieSecurityConfig
StrictCookieSecurityConfig returns a CookieSecurityConfig with strict security settings. Requires Secure, HttpOnly, and SameSite=Strict attributes.
type Doer ¶ added in v1.3.8
type Doer interface {
// Request executes an HTTP request with the given method and URL.
Request(ctx context.Context, method, url string, options ...RequestOption) (*Result, error)
}
Doer is a minimal interface for executing HTTP requests. Users who need custom implementations can implement this smaller interface instead of the full Client interface.
type DomainClient ¶ added in v1.3.0
type DomainClient struct {
*SessionManager
// contains filtered or unexported fields
}
DomainClient provides a client scoped to a specific domain with session management. It maintains cookies and headers across requests and provides convenient methods for making HTTP requests relative to a base URL.
For better flexibility, use the DomainClienter interface instead of the concrete type:
var dc httpc.DomainClienter
dc, err := httpc.NewDomain("https://api.example.com", httpc.DefaultConfig())
func (*DomainClient) Close ¶ added in v1.3.0
func (dc *DomainClient) Close() error
Close closes the underlying HTTP client and releases resources. Returns nil if the receiver or underlying client is nil.
func (*DomainClient) Delete ¶ added in v1.3.0
func (dc *DomainClient) Delete(path string, options ...RequestOption) (*Result, error)
Delete makes a DELETE request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Domain ¶ added in v1.3.8
func (dc *DomainClient) Domain() string
Domain returns the domain name (host without port). Returns empty string if the receiver is nil.
func (*DomainClient) Download ¶ added in v1.5.2
func (dc *DomainClient) Download(ctx context.Context, path string, cfg *DownloadConfig, options ...RequestOption) (*DownloadResult, error)
Download downloads a file from the specified path to cfg.FilePath. Response cookies are captured into the session. Like Request, request options are applied twice internally (once for session capture, once for the actual request) — avoid options with side effects (e.g., counters, nonce generation).
cfg must be non-nil; cfg.FilePath must be set (ErrEmptyFilePath otherwise). Use DefaultDownloadConfig() as the starting point, then set FilePath and any of ProgressCallback / Overwrite / ResumeDownload / Checksum as needed.
func (*DomainClient) Get ¶ added in v1.3.0
func (dc *DomainClient) Get(path string, options ...RequestOption) (*Result, error)
Get makes a GET request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Head ¶ added in v1.3.0
func (dc *DomainClient) Head(path string, options ...RequestOption) (*Result, error)
Head makes a HEAD request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Options ¶ added in v1.3.0
func (dc *DomainClient) Options(path string, options ...RequestOption) (*Result, error)
Options makes an OPTIONS request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Patch ¶ added in v1.3.0
func (dc *DomainClient) Patch(path string, options ...RequestOption) (*Result, error)
Patch makes a PATCH request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Post ¶ added in v1.3.0
func (dc *DomainClient) Post(path string, options ...RequestOption) (*Result, error)
Post makes a POST request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Put ¶ added in v1.3.0
func (dc *DomainClient) Put(path string, options ...RequestOption) (*Result, error)
Put makes a PUT request to the specified path relative to the base URL. If path is a full URL (with scheme), it is used directly.
func (*DomainClient) Request ¶ added in v1.3.8
func (dc *DomainClient) Request(ctx context.Context, method, path string, options ...RequestOption) (*Result, error)
Request makes an HTTP request with the specified method and path relative to the base URL. If path is a full URL (with scheme), it is used directly. The context parameter allows for timeout and cancellation control. This method makes DomainClient compatible with the Client interface.
Note: RequestOptions are executed twice internally — once to capture session state (cookies, headers) and once for the actual request. Avoid options with side effects (e.g., counters, nonce generation) or use the underlying Client directly if needed.
func (*DomainClient) Session ¶ added in v1.3.8
func (dc *DomainClient) Session() *SessionManager
Session returns the underlying SessionManager for advanced session management. Returns nil if the receiver is nil.
func (*DomainClient) URL ¶ added in v1.3.8
func (dc *DomainClient) URL() string
URL returns the base URL. Returns empty string if the receiver is nil.
type DomainClienter ¶ added in v1.3.8
type DomainClienter interface {
Client
// URL accessors
URL() string
Domain() string
// Session header management
SetHeader(key, value string) error
SetHeaders(headers map[string]string) error
DeleteHeader(key string)
ClearHeaders()
GetHeaders() map[string]string
// Session cookie management
SetCookie(cookie *http.Cookie) error
SetCookies(cookies []*http.Cookie) error
DeleteCookie(name string)
ClearCookies()
GetCookies() []*http.Cookie
GetCookie(name string) *http.Cookie
// Session access
Session() *SessionManager
}
DomainClienter extends Client with domain-scoped operations. It provides session management for cookies and headers across requests to a specific domain.
func NewDomain ¶ added in v1.3.0
func NewDomain(baseURL string, cfg Config) (DomainClienter, error)
NewDomain creates a new DomainClient scoped to the specified base URL. The client automatically manages cookies and headers across requests. Pass DefaultConfig() for defaults, or use NewDomainDefault(baseURL) as a zero-argument shortcut. Cookies are automatically enabled for DomainClient.
Returns an error if baseURL does not include a scheme and host, or if the configuration fails validation. See New for configuration error conditions.
Returns a DomainClienter interface for flexibility and testability. Type-assert to *DomainClient if access to the concrete type is needed.
Examples:
// Use default configuration
dc, err := httpc.NewDomain("https://api.example.com", httpc.DefaultConfig())
// Use custom configuration
cfg := httpc.DefaultConfig()
cfg.Timeouts.Request = 60 * time.Second
dc, err := httpc.NewDomain("https://api.example.com", cfg)
// Set session headers
dc.SetHeader("Authorization", "Bearer token")
// Make requests relative to base URL
result, err := dc.Get("/users")
func NewDomainDefault ¶ added in v1.6.0
func NewDomainDefault(baseURL string) (DomainClienter, error)
NewDomainDefault creates a DomainClient scoped to baseURL using DefaultConfig(). It is a convenience shortcut for NewDomain(baseURL, DefaultConfig()), mirroring NewDefault() for the main client.
Example:
dc, err := httpc.NewDomainDefault("https://api.example.com")
defer func() { _ = dc.Close() }()
type DownloadConfig ¶ added in v1.3.9
type DownloadConfig struct {
// FilePath is the destination path for the downloaded file.
FilePath string
// ProgressCallback is called periodically during download to report progress.
ProgressCallback DownloadProgressCallback
// Overwrite allows overwriting an existing file at FilePath.
Overwrite bool
// ResumeDownload attempts to resume a previously interrupted download.
ResumeDownload bool
// Checksum is the expected hex-encoded checksum of the downloaded file.
// When set, the file is verified after download completes.
// A mismatch causes the download to fail and the file to be removed.
Checksum string
// ChecksumAlgorithm specifies the hash algorithm for verification.
// Currently only "sha256" is supported. Default: "sha256".
ChecksumAlgorithm ChecksumAlgorithm
}
DownloadConfig configures file download behavior. Use DefaultDownloadConfig() to get a configuration with sensible defaults.
func DefaultDownloadConfig ¶ added in v1.3.9
func DefaultDownloadConfig() *DownloadConfig
DefaultDownloadConfig returns a DownloadConfig with default settings. Overwrite and ResumeDownload are both false by default. Caller must set FilePath before use.
Example:
cfg := httpc.DefaultDownloadConfig() cfg.FilePath = "/downloads/file.zip" cfg.Overwrite = true result, err := httpc.Download(context.Background(), url, cfg)
type DownloadProgressCallback ¶
DownloadProgressCallback is called during file download to report progress. Parameters: downloaded bytes, total bytes, current speed in bytes/second.
type DownloadResult ¶
type DownloadResult struct {
// FilePath is the path where the file was saved.
FilePath string
// BytesWritten is the total number of bytes written to disk.
BytesWritten int64
// Duration is the total time taken for the download.
Duration time.Duration
// AverageSpeed is the average download speed in bytes/second.
AverageSpeed float64
// StatusCode is the HTTP status code of the download response.
StatusCode int
// ContentLength is the Content-Length reported by the server.
ContentLength int64
// Resumed indicates whether the download was resumed from a previous partial download.
Resumed bool
// ResponseCookies contains cookies returned by the download response.
ResponseCookies []*http.Cookie
// ActualChecksum is the computed checksum of the downloaded file (hex-encoded).
// Only set when DownloadConfig.Checksum is provided.
ActualChecksum string
// Proto is the HTTP protocol version of the response (e.g., "HTTP/1.1", "HTTP/2.0").
Proto string
// ResponseHeaders contains the response headers from the download.
ResponseHeaders http.Header
// RequestURL is the actual URL that was requested.
RequestURL string
// RequestMethod is the HTTP method used for the download.
RequestMethod string
// RequestHeaders contains the request headers that were sent.
RequestHeaders http.Header
}
DownloadResult contains information about a completed download.
func Download ¶ added in v1.5.2
func Download(ctx context.Context, url string, cfg *DownloadConfig, options ...RequestOption) (*DownloadResult, error)
Download downloads a file from url to the path specified in cfg, using the default client with the given context and request options.
Download is the single canonical download entry point across the package, the Client interface, and DomainClient: one signature collapses the former {config} × {context} variant matrix. Callers that already hold a client or DomainClient use the Download method of the same signature.
cfg must be non-nil; cfg.FilePath must be set (ErrEmptyFilePath otherwise). Use context.Background() when no cancellation or timeout is required. Pass options for headers, authentication, query parameters, etc.
type ErrorType ¶ added in v1.3.8
ErrorType represents the classification of an error.
const ( // ErrorTypeUnknown indicates an unknown or unclassified error. ErrorTypeUnknown ErrorType = engine.ErrorTypeUnknown // ErrorTypeNetwork indicates a network-level error (connection refused, DNS failure, etc.). ErrorTypeNetwork ErrorType = engine.ErrorTypeNetwork // ErrorTypeTimeout indicates a timeout occurred during the request. ErrorTypeTimeout ErrorType = engine.ErrorTypeTimeout // ErrorTypeContextCanceled indicates the request context was canceled. ErrorTypeContextCanceled ErrorType = engine.ErrorTypeContextCanceled // ErrorTypeResponseRead indicates an error reading the response body. ErrorTypeResponseRead ErrorType = engine.ErrorTypeResponseRead // ErrorTypeTransport indicates an HTTP transport-level error. ErrorTypeTransport ErrorType = engine.ErrorTypeTransport // ErrorTypeRetryExhausted indicates all retry attempts have been exhausted. ErrorTypeRetryExhausted ErrorType = engine.ErrorTypeRetryExhausted // ErrorTypeTLS indicates a TLS handshake or protocol error. ErrorTypeTLS ErrorType = engine.ErrorTypeTLS // ErrorTypeCertificate indicates a certificate validation error. ErrorTypeCertificate ErrorType = engine.ErrorTypeCertificate // ErrorTypeDNS indicates a DNS resolution error. ErrorTypeDNS ErrorType = engine.ErrorTypeDNS // ErrorTypeValidation indicates a request validation error. ErrorTypeValidation ErrorType = engine.ErrorTypeValidation // ErrorTypeHTTP indicates an HTTP-level error (4xx, 5xx responses). ErrorTypeHTTP ErrorType = engine.ErrorTypeHTTP )
Error type constants for error classification.
type FileData ¶
FileData represents a file to be uploaded in a multipart form. Alias for types.FileData to avoid importing the internal package.
type FormData ¶
FormData represents multipart form data for HTTP requests. Alias for types.FormData to avoid importing the internal package.
Example:
form := &httpc.FormData{
Fields: map[string]string{"key": "value"},
Files: map[string]*httpc.FileData{
"file": {Filename: "test.txt", Content: []byte("hello")},
},
}
type Handler ¶ added in v1.3.8
Handler processes an HTTP request and returns a response. Alias for types.Handler to avoid importing the internal package.
type HeaderConfig ¶ added in v1.6.0
type HeaderConfig struct {
// Headers contains static headers added to every request. Existing headers
// with the same keys are overwritten. Headers are validated for security
// (CRLF injection prevention) at middleware creation time.
// Default: empty (no headers added — the middleware is a pass-through).
Headers map[string]string
}
HeaderConfig configures the header middleware. Use DefaultHeaderConfig() as the starting point.
func DefaultHeaderConfig ¶ added in v1.6.0
func DefaultHeaderConfig() *HeaderConfig
DefaultHeaderConfig returns a HeaderConfig with no headers.
type LoggingConfig ¶ added in v1.6.0
type LoggingConfig struct {
// LogFunc receives formatted log messages (similar to log.Printf).
// If nil, logging is disabled.
LogFunc func(format string, args ...any)
}
LoggingConfig configures the logging middleware. Use DefaultLoggingConfig() as the starting point.
func DefaultLoggingConfig ¶ added in v1.6.0
func DefaultLoggingConfig() *LoggingConfig
DefaultLoggingConfig returns a LoggingConfig with logging disabled. Set LogFunc to enable logging.
type MetricsConfig ¶ added in v1.6.0
type MetricsConfig struct {
// OnMetrics is invoked with request metrics after each request completes.
// If nil, metrics collection is disabled.
OnMetrics func(method, url string, statusCode int, duration time.Duration, err error)
}
MetricsConfig configures the metrics middleware. Use DefaultMetricsConfig() as the starting point.
func DefaultMetricsConfig ¶ added in v1.6.0
func DefaultMetricsConfig() *MetricsConfig
DefaultMetricsConfig returns a MetricsConfig with metrics disabled. Set OnMetrics to enable metrics collection.
type MiddlewareConfig ¶ added in v1.4.0
type MiddlewareConfig struct {
// Middlewares contains middleware functions for request/response interception.
// Default: nil.
Middlewares []MiddlewareFunc
}
MiddlewareConfig configures the middleware chain applied to every outgoing request. Request defaults (User-Agent, headers, redirect policy) live on Config.Defaults (RequestDefaults).
type MiddlewareFunc ¶ added in v1.3.8
type MiddlewareFunc = types.MiddlewareFunc
MiddlewareFunc wraps a Handler with pre/post-processing logic. Alias for types.MiddlewareFunc to avoid importing the internal package.
func AuditMiddleware ¶ added in v1.3.8
func AuditMiddleware(config *AuditConfig) MiddlewareFunc
AuditMiddleware creates a middleware that generates security audit events with configurable output format and options. The callback is supplied via config.OnAudit; if nil, the middleware is a no-op. A nil config selects DefaultAuditConfig().
This middleware is designed for high-security scenarios (financial, medical, government) where comprehensive request logging is required for compliance. SourceIP and UserID are extracted from the request context using SourceIPKey and UserIDKey.
Example:
cfg := httpc.DefaultAuditConfig()
cfg.OnAudit = func(event httpc.AuditEvent) {
log.Printf("[AUDIT] %v", event)
}
cfg.Format = "json"
cfg.IncludeHeaders = true
auditMiddleware := httpc.AuditMiddleware(cfg)
func Chain ¶ added in v1.3.8
func Chain(middlewares ...MiddlewareFunc) MiddlewareFunc
Chain combines multiple middlewares into a single middleware. Middlewares are executed in the order they are provided (first to last). The final handler is executed after all middlewares have processed the request.
func HeaderMiddleware ¶ added in v1.3.8
func HeaderMiddleware(config *HeaderConfig) MiddlewareFunc
HeaderMiddleware creates a middleware that adds static headers to every request, configured via HeaderConfig. A nil config selects DefaultHeaderConfig() (no headers — effectively a pass-through). Existing headers with the same keys will be overwritten. Headers are validated for security (CRLF injection prevention) at middleware creation time.
func LoggingMiddleware ¶ added in v1.3.8
func LoggingMiddleware(config *LoggingConfig) MiddlewareFunc
LoggingMiddleware creates a logging middleware with the given configuration. A nil config selects DefaultLoggingConfig() (logging disabled). SECURITY: URLs are sanitized to remove credentials before logging.
func MetricsMiddleware ¶ added in v1.3.8
func MetricsMiddleware(config *MetricsConfig) MiddlewareFunc
MetricsMiddleware creates a metrics middleware with the given configuration. A nil config selects DefaultMetricsConfig() (metrics disabled).
func RecoveryMiddleware ¶ added in v1.3.8
func RecoveryMiddleware() MiddlewareFunc
RecoveryMiddleware creates a middleware that recovers from panics in the request handler. If a panic occurs, it is converted to an error and returned.
func RequestIDMiddleware ¶ added in v1.3.8
func RequestIDMiddleware(config *RequestIDConfig) MiddlewareFunc
RequestIDMiddleware creates a middleware that adds a unique request ID to each request using the given configuration. A nil config selects DefaultRequestIDConfig() ("X-Request-ID" header, crypto/rand generator).
SECURITY: When Generator is nil, the default uses crypto/rand to produce unpredictable request IDs, preventing request ID guessing attacks.
func TimeoutMiddleware ¶ added in v1.3.8
func TimeoutMiddleware(config *TimeoutMiddlewareConfig) MiddlewareFunc
TimeoutMiddleware creates a middleware that enforces a maximum duration for requests, configured via TimeoutMiddlewareConfig. A nil config selects DefaultTimeoutMiddlewareConfig() (timeout disabled — the middleware is a pass-through). If the request exceeds the timeout, the context is canceled and an error is returned. This timeout applies at the middleware level, before the client's built-in timeout.
Caveat — streaming and Download: this middleware cancels its derived context as soon as the handler returns (defer cancel()), which for Download happens once the response headers have been received but before the body stream is consumed. The cancel therefore fires immediately on the first byte of the body, surfacing as a "context canceled" error long before the requested timeout elapses. Do NOT wrap Download (or any WithStreamBody request) with this middleware; use WithTimeout instead, whose deadline is applied on the engine's overall context and survives the body read.
type ProxyStrategy ¶ added in v1.6.0
ProxyStrategy selects the algorithm for choosing a proxy from a proxy pool. Alias for proxypool.Strategy to avoid importing the internal package.
type RequestDefaults ¶ added in v1.6.0
type RequestDefaults struct {
// UserAgent sets the User-Agent header. Default: "httpc/1.0".
UserAgent string
// Headers contains default headers added to every request.
// Default: empty (no default headers).
Headers map[string]string
// FollowRedirects controls automatic redirect following. Default: true.
FollowRedirects bool
// MaxRedirects limits automatic redirects. Default: 10.
MaxRedirects int
}
RequestDefaults configures per-request defaults applied to every outgoing request: the User-Agent header, default headers, and the redirect policy.
This is the canonical location for request defaults. Use DefaultConfig() to obtain sensible values for all fields, then modify as needed.
type RequestIDConfig ¶ added in v1.6.0
type RequestIDConfig struct {
// HeaderName is the HTTP header name for the request ID.
// Default: "X-Request-ID".
HeaderName string
// Generator produces the request ID string. If nil, a cryptographically
// secure random generator is used (crypto/rand, 16 bytes hex-encoded).
Generator func() string
}
RequestIDConfig configures the request ID middleware. Use DefaultRequestIDConfig() as the starting point.
func DefaultRequestIDConfig ¶ added in v1.6.0
func DefaultRequestIDConfig() *RequestIDConfig
DefaultRequestIDConfig returns a RequestIDConfig with sensible defaults. HeaderName defaults to "X-Request-ID"; Generator defaults to crypto/rand.
type RequestInfo ¶ added in v1.3.0
type RequestInfo struct {
// URL is the request URL.
URL string
// Method is the HTTP method used.
Method string
// Headers contains the request headers.
Headers http.Header
// Cookies contains the request cookies.
Cookies []*http.Cookie
}
RequestInfo contains details about the HTTP request that was sent.
type RequestMeta ¶ added in v1.3.0
type RequestMeta struct {
// Duration is the total time from request start to response completion.
Duration time.Duration
// Attempts is the number of request attempts including retries.
Attempts int
// RedirectChain contains the URLs followed during redirects.
RedirectChain []string
// RedirectCount is the number of redirects followed.
RedirectCount int
}
RequestMeta contains metadata about the request execution including timing and redirect info.
type RequestMutator ¶ added in v1.3.8
type RequestMutator = types.RequestMutator
RequestMutator provides read-write access to request data for middleware. Alias for types.RequestMutator to avoid importing the internal package.
type RequestOption ¶
type RequestOption = engine.RequestOption
RequestOption is a function that modifies a request before it is sent. Alias for engine.RequestOption to avoid importing the internal package.
func WithAllowPrivateIPs ¶ added in v1.5.2
func WithAllowPrivateIPs(allow bool) RequestOption
WithAllowPrivateIPs overrides the client's SSRF policy for this single request. When allow is true, the request may target localhost and private/reserved IP ranges (127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 169.254.0.0/16, etc.) and may follow redirects to such addresses. When allow is false, SSRF protection is enforced for this request even if the client was configured with Security.AllowPrivateIPs=true.
This is a per-request escape hatch from SSRF protection. It is intended for cases where a client that uses secure defaults (AllowPrivateIPs=false) must occasionally reach an internal service, loopback address, or local development server — without relaxing the security posture of the whole client.
SECURITY: Only enable this on requests whose URL is trusted and not derived from untrusted user input. SSRF protection exists to prevent an attacker from making your process reach private/internal endpoints; disabling it per request reopens that risk for this call. For whole-client access to internal services, prefer setting Security.AllowPrivateIPs=true on the Config.
Example (default client blocks private IPs; this call opts in per request):
result, err := httpc.Get("http://localhost:8080/health",
httpc.WithAllowPrivateIPs(true),
)
func WithBasicAuth ¶
func WithBasicAuth(username, password string) RequestOption
WithBasicAuth sets HTTP Basic Authentication using the provided username and password. Returns an error if username is empty, or if username or password exceeds the maximum length or contains invalid characters.
func WithBearerToken ¶
func WithBearerToken(token string) RequestOption
WithBearerToken sets the Authorization header to "Bearer <token>". Returns an error if token is empty or fails token format validation.
func WithBinary ¶
func WithBinary(data []byte, contentType ...string) RequestOption
WithBinary sets binary data as the request body with an optional content type. Returns an error if data is nil.
func WithBody ¶
func WithBody(data any, kind ...BodyKind) RequestOption
WithBody sets the request body with automatic or explicit type detection. When kind is BodyAuto (or omitted), the body type is auto-detected based on the input:
- string → text/plain
- []byte → application/octet-stream
- map[string]string → application/x-www-form-urlencoded
- *FormData → multipart/form-data
- io.Reader → passed through (no Content-Type set)
- other types → application/json (default)
Note: io.Reader bodies bypass request body size validation. For untrusted sources, wrap with io.LimitReader to prevent resource exhaustion:
limited := io.LimitReader(untrustedReader, 10<<20) // 10 MB cap
Explicit kinds (BodyJSON, BodyXML, BodyForm, BodyBinary, BodyMultipart) override auto-detection.
Example:
// Auto-detect (JSON for struct/map) result, err := client.Post(url,httpc.WithBody(data, httpc.BodyAuto)) // Explicit XML result, err := client.Post(url,httpc.WithBody(data, httpc.BodyXML)) // Auto-detect omitted (same as BodyAuto) result, err := client.Post(url,httpc.WithBody(data))
Returns an error if data is nil, or if the body type is incompatible with the specified BodyKind (e.g., BodyMultipart requires *FormData, BodyForm requires map[string]string or url.Values, BodyBinary requires []byte or string).
func WithContext ¶
func WithContext(ctx context.Context) RequestOption
WithContext sets the context for the request, enabling timeout and cancellation control. The context overrides the client's default timeout for this request. Returns an error if ctx is nil.
func WithCookie ¶
func WithCookie(cookie http.Cookie) RequestOption
WithCookie adds a cookie to the request after validation. Returns an error if the cookie name or value fails validation (empty name, control characters, or invalid characters).
func WithCookieMap ¶ added in v1.3.8
func WithCookieMap(cookies map[string]string) RequestOption
WithCookieMap sets multiple cookies from a map of name-value pairs. This is a convenience method for setting multiple simple cookies at once. For cookies with additional attributes (Domain, Path, Secure, etc.), use WithCookie or WithCookieString instead. Returns an error if any cookie name or value fails validation. The error message includes the cookie name that failed.
Example:
cookies := map[string]string{
"session_id": "abc123",
"user_pref": "dark_mode",
"lang": "en",
}
result, err := client.Get("https://api.example.com",
httpc.WithCookieMap(cookies),
)
func WithCookieString ¶ added in v1.3.0
func WithCookieString(cookieString string) RequestOption
WithCookieString adds cookies from a raw Cookie header string to the request. Returns an error if the cookie string is malformed (missing '=' separator, empty name) or if any parsed cookie fails validation.
func WithCookies ¶
func WithCookies(cookies []http.Cookie) RequestOption
WithCookies adds multiple cookies to the request after validation. It is more efficient than calling WithCookie multiple times, as it pre-allocates capacity and validates all cookies in a single pass. Returns an error if any cookie fails validation (empty name, control characters, or invalid characters). The error message includes the cookie name that failed.
Example:
cookies := []http.Cookie{
{Name: "session_id", Value: "abc123"},
{Name: "user_pref", Value: "dark_mode"},
{Name: "lang", Value: "en"},
}
result, err := client.Get("https://api.example.com",
httpc.WithCookies(cookies),
)
func WithFile ¶
func WithFile(fieldName, filename string, content []byte) RequestOption
WithFile adds a file upload to the request as multipart/form-data. Returns an error if fieldName or filename is empty, contains invalid characters, or resolves to an invalid path (e.g., ".." or ".").
func WithFollowRedirects ¶ added in v1.3.0
func WithFollowRedirects(follow bool) RequestOption
WithFollowRedirects controls whether HTTP redirects are followed for this request.
func WithForm ¶
func WithForm(data map[string]string) RequestOption
WithForm sets the request body as URL-encoded form data. Each field key and value is validated for control characters and size limits. This is a convenience method with per-field validation; the general-purpose alternative is WithBody(data, BodyForm). Returns an error if data is nil, or if any field key or value contains control characters or exceeds the maximum length.
func WithFormData ¶
func WithFormData(data *FormData) RequestOption
WithFormData sets the request body as multipart/form-data. This is a convenience method; the equivalent is WithBody(data, BodyMultipart). Returns an error if data is nil.
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader sets a single HTTP header on the request. Returns ErrInvalidHeader if the key or value contains invalid characters (CRLF injection prevention).
func WithHeaderMap ¶
func WithHeaderMap(headers map[string]string) RequestOption
WithHeaderMap sets multiple headers from a map. Returns ErrInvalidHeader if any key or value contains invalid characters (CRLF injection prevention).
func WithJSON ¶
func WithJSON(data any) RequestOption
WithJSON sets the request body as JSON and sets Content-Type to application/json. This is a convenience method; the equivalent is WithBody(data, BodyJSON). Returns an error if data is nil.
func WithMaxRedirects ¶ added in v1.3.0
func WithMaxRedirects(maxRedirects int) RequestOption
WithMaxRedirects sets the maximum number of redirects to follow for this request. Returns an error if maxRedirects is negative or exceeds 50.
Note: a value of 0 does NOT disable redirects. The engine treats 0 as the "not explicitly set" sentinel and falls back to the default limit (10), so WithMaxRedirects(0) is equivalent to omitting the option. To disable redirect following entirely, use WithFollowRedirects(false) instead.
func WithMaxRetries ¶
func WithMaxRetries(maxRetries int) RequestOption
WithMaxRetries sets the maximum number of retry attempts for this request. Returns ErrInvalidRetry if maxRetries is negative or exceeds 10.
func WithOnRequest ¶ added in v1.3.8
func WithOnRequest(callback func(req RequestMutator) error) RequestOption
WithOnRequest registers a callback invoked before the request is sent. The callback receives the request mutator, allowing inspection or modification of the request before it's transmitted.
Multiple callbacks can be chained - they are executed in the order added. If any callback returns an error, the request is aborted.
Example:
result, err := client.Get("https://api.example.com",
httpc.WithOnRequest(func(req httpc.RequestMutator) error {
log.Printf("Sending %s request to %s", req.Method(), req.URL())
return nil
}),
)
Returns an error if callback is nil.
func WithOnResponse ¶ added in v1.3.8
func WithOnResponse(callback func(resp ResponseMutator) error) RequestOption
WithOnResponse registers a callback invoked after the response is received. The callback receives the response mutator, allowing inspection or modification of the response before it's returned to the caller.
Multiple callbacks can be chained - they are executed in the order added. If any callback returns an error, the request fails with that error.
Example:
result, err := client.Get("https://api.example.com",
httpc.WithOnResponse(func(resp httpc.ResponseMutator) error {
log.Printf("Received response: %d %s", resp.StatusCode(), resp.Status())
return nil
}),
)
Returns an error if callback is nil.
func WithQuery ¶
func WithQuery(key string, value any) RequestOption
WithQuery sets a single query parameter on the request. Returns an error if the key is empty, too long, or contains invalid characters, or if the formatted value exceeds the maximum allowed length.
func WithQueryMap ¶
func WithQueryMap(params map[string]any) RequestOption
WithQueryMap sets multiple query parameters from a map. Returns an error if any key is empty, too long, or contains invalid characters, or if any formatted value exceeds the maximum allowed length.
func WithSecureCookie ¶ added in v1.3.8
func WithSecureCookie(securityConfig *CookieSecurityConfig) RequestOption
WithSecureCookie creates a request option that enforces cookie security attributes on cookies already added to the request. The securityConfig defines the required security attributes (Secure, HttpOnly, SameSite).
IMPORTANT: This option validates only cookies present at the time it is applied. Place WithSecureCookie AFTER all WithCookie/WithCookieMap options:
// Correct order: add cookies first, then validate
result, err := client.Get(url,
httpc.WithCookie(sessionCookie),
httpc.WithCookieMap(otherCookies),
httpc.WithSecureCookie(securityConfig),
)
For session-level cookie security that validates all cookies regardless of order, use SessionManager.SetCookieSecurity instead.
Example:
security := &httpc.CookieSecurityConfig{
RequireSecure: true,
RequireHttpOnly: true,
RequireSameSite: "Strict",
AllowSameSiteNone: false,
}
result, err := client.Get("https://api.example.com",
httpc.WithSecureCookie(security),
)
Returns an error if securityConfig is nil, or if any cookie on the request fails the security validation check.
func WithStreamBody ¶ added in v1.4.0
func WithStreamBody(stream bool) RequestOption
WithStreamBody enables streaming mode where the response body is not buffered into memory; the body is read directly via the engine Response's RawBodyReader.
IMPORTANT: streaming is only effective through Download (and any other path that consumes the engine Response directly). When used with the standard request methods — Get, Post, Put, Patch, Delete, Head, Options, or Request — the response is converted to a Result whose body is fully read, and the underlying stream is then closed by the deferred response release. The returned Result therefore has an empty body, and the stream cannot be consumed by the caller. To actually stream a large body without buffering, use Download.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) RequestOption
WithTimeout sets a per-request timeout that overrides the client's default timeout. Returns ErrInvalidTimeout if timeout is negative or exceeds 30 minutes.
func WithUserAgent ¶
func WithUserAgent(userAgent string) RequestOption
WithUserAgent sets the User-Agent header. This is kept as a convenience function since it's commonly used.
func WithXML ¶
func WithXML(data any) RequestOption
WithXML sets the request body as XML and sets Content-Type to application/xml. This is a convenience method; the equivalent is WithBody(data, BodyXML). Returns an error if data is nil.
type ResponseInfo ¶ added in v1.3.0
type ResponseInfo struct {
// StatusCode is the HTTP status code.
StatusCode int
// Status is the HTTP status text.
Status string
// Proto is the HTTP protocol version.
Proto string
// Headers contains the response headers.
Headers http.Header
// Body is the response body as a string.
Body string
// RawBody is the raw response body bytes.
RawBody []byte
// ContentLength is the Content-Length from the response.
ContentLength int64
// Cookies contains the response cookies.
Cookies []*http.Cookie
}
ResponseInfo contains the HTTP response data including status, headers, body, and cookies.
type ResponseMutator ¶ added in v1.3.8
type ResponseMutator = types.ResponseMutator
ResponseMutator provides read-write access to response data for middleware. Alias for types.ResponseMutator to avoid importing the internal package.
type Result ¶ added in v1.3.0
type Result struct {
Request *RequestInfo
Response *ResponseInfo
Meta *RequestMeta
}
Result wraps an HTTP response with request metadata and convenience methods. Obtain a Result from Client.Request() or package-level functions like Get(), Post(), etc. Each Result is freshly allocated per request; GC reclaims it automatically, so callers need not release it. (The internal engine.Response is pooled separately for performance, but that is transparent to the caller.)
Access style: prefer the nil-safe accessor methods (StatusCode, Body, RawBody, IsSuccess, GetCookie, etc.). The Request, Response, and Meta struct fields are exported primarily so callers can construct Result values directly in tests and mocks; reading them on a client-returned Result requires a nil-check on the nested pointer (e.g. Response may be nil when the request errored).
func Delete ¶
func Delete(url string, options ...RequestOption) (*Result, error)
Delete makes a DELETE request to the specified URL using the default client.
func Get ¶
func Get(url string, options ...RequestOption) (*Result, error)
Get makes a GET request to the specified URL using the default client.
func Head ¶
func Head(url string, options ...RequestOption) (*Result, error)
Head makes a HEAD request to the specified URL using the default client.
func Options ¶
func Options(url string, options ...RequestOption) (*Result, error)
Options makes an OPTIONS request to the specified URL using the default client.
func Patch ¶
func Patch(url string, options ...RequestOption) (*Result, error)
Patch makes a PATCH request to the specified URL using the default client.
func Post ¶
func Post(url string, options ...RequestOption) (*Result, error)
Post makes a POST request to the specified URL using the default client.
func Put ¶
func Put(url string, options ...RequestOption) (*Result, error)
Put makes a PUT request to the specified URL using the default client.
func Request ¶
Request executes an HTTP request with the given method using the default client. The context parameter allows for timeout and cancellation control.
Example:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := httpc.Request(ctx, "GET", "https://api.example.com/data")
func (*Result) Body ¶ added in v1.3.0
Body returns the response body as a string. Returns an empty string if the Result or Response is nil.
func (*Result) GetCookie ¶ added in v1.3.0
GetCookie returns a response cookie by name, or nil if not found.
func (*Result) GetRequestCookie ¶ added in v1.3.0
GetRequestCookie returns a request cookie by name, or nil if not found.
func (*Result) HasCookie ¶ added in v1.3.0
HasCookie returns true if a response cookie with the given name exists.
func (*Result) HasRequestCookie ¶ added in v1.3.0
HasRequestCookie returns true if a request cookie with the given name exists.
func (*Result) IsClientError ¶ added in v1.3.0
IsClientError returns true if the response status code indicates a client error (4xx).
func (*Result) IsRedirect ¶ added in v1.3.0
IsRedirect returns true if the response status code indicates a redirect (3xx).
func (*Result) IsServerError ¶ added in v1.3.0
IsServerError returns true if the response status code indicates a server error (5xx).
func (*Result) IsSuccess ¶ added in v1.3.0
IsSuccess returns true if the response status code indicates success (2xx).
func (*Result) Proto ¶ added in v1.3.8
Proto returns the HTTP protocol version (e.g., "HTTP/1.1", "HTTP/2.0").
func (*Result) RawBody ¶ added in v1.3.0
RawBody returns the response body as a byte slice. Returns nil if the Result or Response is nil.
func (*Result) RequestCookies ¶ added in v1.3.0
RequestCookies returns the cookies that were sent with the request. Returns nil if the Result or Request is nil.
func (*Result) ResponseCookies ¶ added in v1.3.0
ResponseCookies returns the cookies from the response. Returns nil if the Result or Response is nil.
func (*Result) SaveToFile ¶ added in v1.3.0
SaveToFile saves the response body to a file at the specified path. Returns ErrResponseBodyEmpty if the response body is nil or empty. The file path is validated for security (path traversal, symlinks, etc.).
func (*Result) StatusCode ¶ added in v1.3.0
StatusCode returns the HTTP status code from the response. Returns 0 if the Result or Response is nil.
func (*Result) String ¶ added in v1.3.0
String returns a human-readable representation of the Result. Sensitive headers are masked. Body is truncated to 200 characters.
func (*Result) Unmarshal ¶ added in v1.3.8
Unmarshal parses the JSON-encoded response body and stores the result in the value pointed to by v. It follows the same conventions as json.Unmarshal.
Returns ErrResponseBodyEmpty if the body is nil or empty. Returns ErrResponseBodyTooLarge if the body exceeds 50MB.
type RetryConfig ¶ added in v1.4.0
type RetryConfig struct {
// MaxRetries is the maximum retry attempts. Default: 3. Set to 0 to disable.
MaxRetries int
// Delay is the initial retry delay. Default: 1s.
Delay time.Duration
// BackoffFactor multiplies Delay after each failed attempt. Default: 2.0.
BackoffFactor float64
// EnableJitter enables jitter in retry delay. Default: true.
EnableJitter bool
// MaxRetryDelay caps the maximum delay between retry attempts.
// Default: 30s. Set to 0 for no cap (not recommended).
MaxRetryDelay time.Duration
// CustomPolicy overrides the built-in retry logic. Default: nil.
CustomPolicy RetryPolicy
}
RetryConfig configures retry behavior for transient failures.
type RetryPolicy ¶ added in v1.3.8
type RetryPolicy = types.RetryPolicy
RetryPolicy defines the interface for custom retry behavior. Alias for types.RetryPolicy to avoid importing the internal package.
type SecurityConfig ¶ added in v1.4.0
type SecurityConfig struct {
// TLSConfig provides custom TLS configuration. If set, MinTLSVersion and
// MaxTLSVersion are ignored. Default: nil.
TLSConfig *tls.Config
// MinTLSVersion is the minimum TLS version. Default: TLS 1.2.
MinTLSVersion uint16
// MaxTLSVersion is the maximum TLS version. Default: TLS 1.3.
MaxTLSVersion uint16
// InsecureSkipVerify disables TLS certificate verification.
// WARNING: Only use in testing. Default: false.
InsecureSkipVerify bool
// MaxResponseBodySize limits response body size in bytes. Default: 10MB.
MaxResponseBodySize int64
// MaxRequestBodySize limits request body size in bytes.
// Default: 0 (no request body limit). Unlike MaxResponseBodySize there is
// NO automatic fallback — set it explicitly to enforce an upload cap.
MaxRequestBodySize int64
// MaxDecompressedBodySize limits decompressed response body size in bytes.
// This prevents decompression bomb (zip bomb) attacks. Default: 100MB.
// Only applies when MaxResponseBodySize is not explicitly set; when set,
// MaxResponseBodySize takes precedence as the stricter limit.
MaxDecompressedBodySize int64
// AllowPrivateIPs disables ALL SSRF protection when set to true, including
// localhost, loopback, link-local, and private/reserved IP checks.
// Default: false (SSRF protection enabled). Set to true only when
// connecting to internal services (VPNs, proxies, corporate networks).
// WARNING: This completely bypasses the connection-level SSRF dialer validation,
// not just private IP blocking. Use SSRFExemptCIDRs for selective allowlisting instead.
AllowPrivateIPs bool
// SSRFExemptCIDRs specifies CIDR ranges exempted from SSRF blocking.
// When AllowPrivateIPs is false, IPs matching these CIDRs are still allowed.
// Useful for VPN/Tailscale (100.64.0.0/10) or VPC (10.0.0.0/8) access.
// Invalid CIDRs cause New() to return an error.
SSRFExemptCIDRs []string
// ValidateURL enables URL validation. Default: true.
ValidateURL bool
// ValidateHeaders enables header validation. Default: true.
ValidateHeaders bool
// StrictContentLength enables strict Content-Length validation. Default: true.
StrictContentLength bool
// CookieSecurity enables cookie security attribute validation.
// Default: nil (no validation).
CookieSecurity *CookieSecurityConfig
// CertificatePinner, when set, enables certificate pinning: the TLS
// handshake is rejected unless the server presents a pinned key/certificate,
// defending against MITM even if a trusted CA is compromised.
// Construct one with NewSPKIHashPinner, NewPublicKeyPinner, or
// NewCertificatePinnerChain. Default: nil (pinning disabled).
//
// The pinner is shared by reference across clients created from the same
// Config (it is not deep-copied); pinner implementations are safe for
// concurrent use by multiple clients.
CertificatePinner CertificatePinner
// RedirectWhitelist specifies allowed domains for redirects.
// Default: nil (all redirects allowed).
RedirectWhitelist []string
}
SecurityConfig configures TLS, validation, and SSRF protection.
type SessionConfig ¶ added in v1.3.9
type SessionConfig struct {
// CookieSecurity configures cookie security validation.
// If nil, no cookie security validation is performed.
CookieSecurity *CookieSecurityConfig
}
SessionConfig configures SessionManager behavior. Use DefaultSessionConfig() to get a configuration with sensible defaults.
func DefaultSessionConfig ¶ added in v1.3.9
func DefaultSessionConfig() SessionConfig
DefaultSessionConfig returns a SessionConfig with default settings. By default, no cookie security validation is performed.
Example:
cfg := httpc.DefaultSessionConfig() cfg.CookieSecurity = validation.StrictCookieSecurityConfig() sm, err := httpc.NewSessionManager(cfg)
type SessionManager ¶ added in v1.3.8
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages session state including cookies and headers for DomainClient instances. It provides thread-safe access to session data.
func NewSessionManager ¶ added in v1.3.8
func NewSessionManager(cfg SessionConfig) (*SessionManager, error)
NewSessionManager creates a new SessionManager with the given configuration. Pass DefaultSessionConfig() for defaults, or use NewSessionManagerDefault() as a zero-argument shortcut.
Example:
cfg := httpc.DefaultSessionConfig() cfg.CookieSecurity = mySecurityConfig sm, err := httpc.NewSessionManager(cfg)
Currently always returns a nil error; the error return is reserved for future validation.
func NewSessionManagerDefault ¶ added in v1.6.0
func NewSessionManagerDefault() (*SessionManager, error)
NewSessionManagerDefault creates a SessionManager with default settings. It is a convenience shortcut for NewSessionManager(DefaultSessionConfig()), mirroring NewDefault() for the main client.
Example:
sm, err := httpc.NewSessionManagerDefault()
func (*SessionManager) ClearCookies ¶ added in v1.3.8
func (s *SessionManager) ClearCookies()
ClearCookies removes all cookies from the session.
func (*SessionManager) ClearHeaders ¶ added in v1.3.8
func (s *SessionManager) ClearHeaders()
ClearHeaders removes all headers from the session.
func (*SessionManager) DeleteCookie ¶ added in v1.3.8
func (s *SessionManager) DeleteCookie(name string)
DeleteCookie removes a cookie from the session by name.
func (*SessionManager) DeleteHeader ¶ added in v1.3.8
func (s *SessionManager) DeleteHeader(key string)
DeleteHeader removes a header from the session.
func (*SessionManager) GetCookie ¶ added in v1.3.8
func (s *SessionManager) GetCookie(name string) *http.Cookie
GetCookie returns a copy of a cookie by name, or nil if not found.
func (*SessionManager) GetCookies ¶ added in v1.3.8
func (s *SessionManager) GetCookies() []*http.Cookie
GetCookies returns a copy of all session cookies. Optimized to reduce allocations by pre-allocating slice with exact capacity.
func (*SessionManager) GetHeaders ¶ added in v1.3.8
func (s *SessionManager) GetHeaders() map[string]string
GetHeaders returns a copy of all session headers.
func (*SessionManager) SetCookie ¶ added in v1.3.8
func (s *SessionManager) SetCookie(cookie *http.Cookie) error
SetCookie adds or updates a cookie in the session. Returns an error if the cookie is nil or invalid. If cookie security is configured, validates against security requirements.
func (*SessionManager) SetCookieSecurity ¶ added in v1.3.8
func (s *SessionManager) SetCookieSecurity(config *CookieSecurityConfig)
SetCookieSecurity sets the cookie security configuration. This affects all subsequent SetCookie calls.
func (*SessionManager) SetCookies ¶ added in v1.3.8
func (s *SessionManager) SetCookies(cookies []*http.Cookie) error
SetCookies adds or updates multiple cookies in the session. Returns an error if any cookie is nil or invalid. If cookie security is configured, validates against security requirements.
func (*SessionManager) SetHeader ¶ added in v1.3.8
func (s *SessionManager) SetHeader(key, value string) error
SetHeader adds or updates a header in the session. Returns an error if the header key or value is invalid.
func (*SessionManager) SetHeaders ¶ added in v1.3.8
func (s *SessionManager) SetHeaders(headers map[string]string) error
SetHeaders adds or updates multiple headers in the session. Returns an error if any header key or value is invalid.
func (*SessionManager) UpdateFromCookies ¶ added in v1.4.0
func (s *SessionManager) UpdateFromCookies(cookies []*http.Cookie)
UpdateFromCookies updates session cookies from a slice of http.Cookie. If cookie security is configured, insecure cookies are silently skipped.
func (*SessionManager) UpdateFromResult ¶ added in v1.3.8
func (s *SessionManager) UpdateFromResult(result *Result)
UpdateFromResult updates session cookies from a Result. If cookie security is configured, insecure cookies are silently skipped.
type TimeoutConfig ¶ added in v1.4.0
type TimeoutConfig struct {
// Request is the overall request timeout including retries.
// Default: 180s. Set to 0 for no timeout (not recommended for production).
Request time.Duration
// Dial is the maximum time to wait for a TCP connection.
// Default: 10s.
Dial time.Duration
// TLSHandshake is the maximum time to wait for TLS handshake.
// Default: 10s. Only applies to HTTPS connections.
TLSHandshake time.Duration
// ResponseHeader is the maximum time to wait for response headers after
// the request is fully written. This timeout is enforced at the transport
// level and applies to ALL requests sharing the same client — it CANNOT
// be overridden per-request via WithTimeout.
//
// When set to 0 (default), the context-level timeout from Timeouts.Request
// or WithTimeout() serves as the sole timeout mechanism, giving per-request
// control over how long to wait for a response.
//
// Set to a positive value ONLY when you want a hard transport-level cap
// independent of the request timeout (e.g., defense-in-depth against
// slowloris attacks). Be aware this will override WithTimeout if the
// ResponseHeader value is shorter.
ResponseHeader time.Duration
// IdleConn is the maximum time an idle connection remains open.
// Default: 90s.
IdleConn time.Duration
}
TimeoutConfig configures timeout behavior for HTTP requests. All duration values use time.Duration (e.g., 30 * time.Second).
type TimeoutMiddlewareConfig ¶ added in v1.6.0
type TimeoutMiddlewareConfig struct {
// Duration is the maximum time allowed for the request. Zero or negative
// disables the timeout (the middleware passes the request through unchanged).
// Default: 0 (disabled).
Duration time.Duration
}
TimeoutMiddlewareConfig configures the timeout middleware. The name includes "Middleware" to distinguish it from the client-level TimeoutConfig in types.go. Use DefaultTimeoutMiddlewareConfig() as the starting point.
func DefaultTimeoutMiddlewareConfig ¶ added in v1.6.0
func DefaultTimeoutMiddlewareConfig() *TimeoutMiddlewareConfig
DefaultTimeoutMiddlewareConfig returns a TimeoutMiddlewareConfig with the timeout disabled. Set Duration to a positive value to enable the timeout.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
concurrency
Package concurrency houses concurrent-safety integration tests for the httpc library.
|
Package concurrency houses concurrent-safety integration tests for the httpc library. |
|
connection
Package connection manages HTTP connection pooling, TLS configuration, and proxy detection for the httpc library.
|
Package connection manages HTTP connection pooling, TLS configuration, and proxy detection for the httpc library. |
|
dns
Package dns provides DNS-over-HTTPS resolution with caching support for the httpc library.
|
Package dns provides DNS-over-HTTPS resolution with caching support for the httpc library. |
|
engine
Package engine implements the core HTTP client engine with request processing, response handling, connection pooling, retry logic, and middleware support.
|
Package engine implements the core HTTP client engine with request processing, response handling, connection pooling, retry logic, and middleware support. |
|
proxy
Package proxy detects system proxy configuration for the httpc library.
|
Package proxy detects system proxy configuration for the httpc library. |
|
proxypool
Package proxypool provides a rotating proxy pool with passive health checking and circuit breaking for the httpc library.
|
Package proxypool provides a rotating proxy pool with passive health checking and circuit breaking for the httpc library. |
|
security
Package security provides request validation, SSRF protection, domain whitelisting, and certificate pinning for the httpc library.
|
Package security provides request validation, SSRF protection, domain whitelisting, and certificate pinning for the httpc library. |
|
types
Package types provides shared type definitions used across the httpc library.
|
Package types provides shared type definitions used across the httpc library. |
|
validation
Package validation provides input sanitization and validation utilities for credentials, headers, cookies, URLs, and network addresses.
|
Package validation provides input sanitization and validation utilities for credentials, headers, cookies, URLs, and network addresses. |