httpc

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 34 Imported by: ? modules, 0 packages

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

README

HTTPC - Secure HTTP Client for Go

Go Version Go Reference License Security Dependencies Thread Safe

A fast, secure HTTP client library for Go with sensible defaults, a lean dependency set, and built-in resilience.

中文文档 | www.cybergo.dev/httpc


Table of Contents


Features

Feature Description
Secure by Default TLS 1.2+, SSRF protection, CRLF injection prevention, path traversal blocking
High Performance Connection pooling, HTTP/2, goroutine-safe, sync.Pool optimization
Built-in Resilience Smart retry with exponential backoff and jitter — non-idempotent requests (POST/PATCH) execute exactly once by default
Automatic Decompression Transparent gzip/deflate handling with zip-bomb protection
Developer Friendly Clean API, intuitive options pattern, comprehensive documentation
Dependencies 7 direct modules — golang.org/x/net + golang.org/x/sys for the standard path, plus brotli / compress / uTLS / tls-client used only by Security.TLSFingerprint
Cookie Management Full cookie jar support with security validation
File Operations Secure file download with progress tracking and resume support
Streaming io.Reader request bodies, zero-copy io.Pipe uploads, disk-streaming downloads

Installation

go get -u github.com/cybergodev/httpc

Requirements: Go 1.27+


Quick Start (5 Minutes)

Simple GET Request
package main

import (
    "fmt"
    "log"

    "github.com/cybergodev/httpc"
)

func main() {
    // Package-level function - convenient for simple requests
    result, err := httpc.Get("https://httpbin.org/get")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Status: %d, Duration: %v\n", result.StatusCode(), result.Meta.Duration)
}
POST JSON with Authentication
package main

import (
    "fmt"
    "log"
    "time"

    "github.com/cybergodev/httpc"
)

func main() {
    user := map[string]string{"name": "John", "email": "john@example.com"}
    result, err := httpc.Post("https://httpbin.org/post",
        httpc.WithJSON(user),
        httpc.WithBearerToken("your-token"),
        httpc.WithTimeout(30*time.Second),
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Response: %s\n", result.Body())
}
package main

import (
    "fmt"
    "log"

    "github.com/cybergodev/httpc"
)

func main() {
    // Create a reusable client with default configuration
    client, err := httpc.NewDefault()
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Make multiple requests
    result, err := client.Get("https://api.example.com/users",
        httpc.WithQuery("page", 1),
        httpc.WithQuery("limit", 20),
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Status: %d\n", result.StatusCode())
}

HTTP Methods

// GET with query parameters
result, _ := httpc.Get("https://api.example.com/users",
    httpc.WithQuery("page", 1),
    httpc.WithQueryMap(map[string]any{"limit": 20}),
)

// POST JSON body
result, _ := httpc.Post("https://api.example.com/users",
    httpc.WithJSON(map[string]string{"name": "John"}),
)

// PUT / PATCH / DELETE
result, _ := httpc.Put(url, httpc.WithJSON(data))
result, _ := httpc.Patch(url, httpc.WithJSON(partialData))
result, _ := httpc.Delete(url)

// HEAD / OPTIONS
result, _ := httpc.Head(url)
result, _ := httpc.Options(url)

// Generic request with custom method
result, _ := httpc.Request(ctx, "PROPFIND", url)

Request Options

Headers
// Single header
httpc.WithHeader("Authorization", "Bearer token")

// Multiple headers
httpc.WithHeaderMap(map[string]string{
    "X-Custom":      "value",
    "X-Request-ID":  "123",
})

// User-Agent
httpc.WithUserAgent("my-app/1.0")
Authentication
// Bearer token
httpc.WithBearerToken("your-jwt-token")

// Basic auth
httpc.WithBasicAuth("username", "password")
Query Parameters
// Single parameter
httpc.WithQuery("page", 1)

// Multiple parameters
httpc.WithQueryMap(map[string]any{"page": 1, "limit": 20})
Request Body
// JSON
httpc.WithJSON(data)

// XML
httpc.WithXML(data)

// Form data (application/x-www-form-urlencoded)
httpc.WithForm(map[string]string{"key": "value"})

// Multipart form data (file upload)
formData := &httpc.FormData{
    Fields: map[string]string{"key": "value"},
    Files: map[string]*httpc.FileData{
        "upload": {Filename: "doc.pdf", Content: fileBytes, ContentType: "application/pdf"},
    },
}
httpc.WithFormData(formData)

// Or use shorthand for single file upload
httpc.WithFile("file", "document.pdf", fileBytes)

// Raw body (auto-detect Content-Type)
httpc.WithBody([]byte("raw data"))
httpc.WithBody(data, httpc.BodyJSON) // explicit BodyKind

// io.Reader body (streamed upload; set Content-Type explicitly)
httpc.WithBody(fileReader)

// BodyKind constants: BodyAuto, BodyJSON, BodyXML, BodyForm, BodyBinary, BodyMultipart

httpc.WithBinary(binaryData, "application/pdf")

// Stream response body (effective only with Download; see Streaming Bodies)
httpc.WithStreamBody(true)
Cookies
// Single cookie
httpc.WithCookies([]http.Cookie{{Name: "session", Value: "abc123"}})

// Batch multiple cookies (efficient, pre-allocates capacity)
httpc.WithCookies([]http.Cookie{
    {Name: "session_id", Value: "abc123"},
    {Name: "user_pref", Value: "dark_mode"},
})

// Multiple cookies from map
httpc.WithCookieMap(map[string]string{
    "session_id": "abc123",
    "user_pref":  "dark_mode",
})

// Cookie string
httpc.WithCookieString("session=abc123; token=xyz")

// Secure cookie with validation (validates cookie security attributes)
cfg := httpc.DefaultCookieSecurityConfig()
cfg.RequireSecure = true
httpc.WithSecureCookie(cfg)
Request Control
// Context for cancellation
httpc.WithContext(ctx)

// Timeout
httpc.WithTimeout(30 * time.Second)

// Retry configuration
httpc.WithMaxRetries(3)

// Lift the client-level timeout for one slow call
httpc.WithNoTimeout()

// Opt in to retrying a non-idempotent method (replay-safe endpoints only)
httpc.WithRetryNonIdempotent(true)

// Redirect control
httpc.WithFollowRedirects(false)
httpc.WithMaxRedirects(5)

// Per-request SSRF override (escape hatch for one trusted internal URL)
httpc.WithAllowPrivateIPs(true)
Callbacks
// Before request
httpc.WithOnRequest(func(req httpc.RequestMutator) error {
    log.Printf("Sending %s %s", req.Method(), req.URL())
    return nil
})

// After response
httpc.WithOnResponse(func(resp httpc.ResponseMutator) error {
    log.Printf("Received %d", resp.StatusCode())
    return nil
})
Complete Options Reference
Category Options
Headers WithHeader(key, value), WithHeaderMap(map), WithUserAgent(ua)
Auth WithBearerToken(token), WithBasicAuth(user, pass)
Query WithQuery(key, value), WithQueryMap(map)
Body WithJSON(data), WithXML(data), WithForm(map), WithFormData(*FormData), WithFile(field, filename, content), WithBody(data, ...BodyKind), WithBinary([]byte, ...contentType), WithStreamBody(bool)
Cookies WithCookies([]http.Cookie), WithCookieMap(map), WithCookieString("a=1; b=2"), WithSecureCookie(config)
Control WithTimeout(dur), WithNoTimeout(), WithMaxRetries(n), WithRetryNonIdempotent(bool), WithContext(ctx), WithAllowPrivateIPs(bool)
Redirects WithFollowRedirects(bool), WithMaxRedirects(n)
Callbacks WithOnRequest(fn), WithOnResponse(fn)

Response Handling

result, _ := httpc.Get("https://api.example.com/users/123")

// Result struct composition:
// result.Request  -> *RequestInfo  (URL, Method, Headers, Cookies)
// result.Response -> *ResponseInfo (StatusCode, Status, Proto, Headers, Body, RawBody, ContentLength, Cookies)
// result.Meta     -> *RequestMeta  (Duration, Attempts, ProxyURL, RedirectCount, RedirectChain)

// Quick access methods (nil-safe)
fmt.Println(result.StatusCode())     // 200
fmt.Println(result.Proto())          // "HTTP/1.1" or "HTTP/2.0"
fmt.Println(result.RawBody())        // Response body ([]byte)
fmt.Println(result.Body())           // Response body (string)

// Status checks
if result.IsSuccess() { }            // 2xx
if result.IsRedirect() { }           // 3xx
if result.IsClientError() { }        // 4xx
if result.IsServerError() { }        // 5xx

// Parse JSON response
var data map[string]interface{}
if err := result.Unmarshal(&data); err != nil {
    log.Fatal(err)
}

// Cookie access
cookie := result.GetCookie("session")
if result.HasCookie("session") { }

// Request cookies sent
reqCookie := result.GetRequestCookie("token")
if result.HasRequestCookie("token") { }

// Get all cookies
allResponse := result.ResponseCookies()
allRequest := result.RequestCookies()

// Save response to file
if err := result.SaveToFile("response.json"); err != nil {
    log.Fatal(err)
}

// Metadata
fmt.Println(result.Meta.Duration)      // Request duration
fmt.Println(result.Meta.Attempts)      // Retry count
fmt.Println(result.Meta.ProxyURL)      // Proxy that served the request ("" = direct)
fmt.Println(result.Meta.RedirectCount) // Redirect count
fmt.Println(result.Meta.RedirectChain) // Redirect URLs

// String representation (safe for logging - masks sensitive headers)
fmt.Println(result.String())
Automatic Decompression

HTTPC transparently decompresses gzip and deflate responses. It advertises Accept-Encoding: gzip, deflate by default (override or extend it with WithHeader("Accept-Encoding", ...)). A decompression-bomb guard caps the decompressed size at Security.MaxDecompressedBodySize (default 100 MB).

result, _ := httpc.Get("https://httpbin.org/gzip",
    httpc.WithHeaderMap(map[string]string{"Accept-Encoding": "gzip, deflate"}),
)
fmt.Println(result.Body()) // already decompressed

Note: Any Content-Encoding other than gzip, deflate and identity (e.g. Brotli br, LZW compress, zstd, or a multi-token list like gzip, br) is rejected with an error instead of silently returning raw compressed bytes as the body. Since httpc only advertises gzip, deflate, this normally only happens if you set Accept-Encoding manually.

Streaming: requests with WithStreamBody(true) (including Download) send Accept-Encoding: identity — the streaming path hands you the raw transport bytes, so it never requests compressed content. A manual Accept-Encoding on a streaming request is honored as-is.


Context & Cancellation

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

result, err := httpc.Get("https://api.example.com",
    httpc.WithContext(ctx),
)
if errors.Is(err, context.DeadlineExceeded) {
    fmt.Println("Request timed out")
}

File Download

Simple Download

File downloads include built-in security protections:

  • UNC path blocking - Prevents access to Windows network paths
  • System path protection - Blocks writes to critical system directories
  • Path traversal detection - Prevents directory escape attacks
  • Resume support - Automatically resumes interrupted downloads
result, _ := httpc.Download(context.Background(),
    "https://example.com/file.zip",
    &httpc.DownloadConfig{FilePath: "downloads/file.zip"},
)
fmt.Printf("Downloaded: %s at %s/s\n",
    httpc.FormatBytes(result.BytesWritten),
    httpc.FormatSpeed(result.AverageSpeed))
Download with Progress
opts := httpc.DefaultDownloadConfig()
opts.FilePath = "downloads/large.zip"
opts.ProgressCallback = func(downloaded, total int64, speed float64) {
    pct := float64(downloaded) / float64(total) * 100
    fmt.Printf("\r%.1f%% - %s/s", pct, httpc.FormatSpeed(speed))
}
result, _ := httpc.Download(context.Background(), url, opts)
Resume Download
opts := httpc.DefaultDownloadConfig()
opts.FilePath = "downloads/large.zip"
opts.ResumeDownload = true
result, _ := httpc.Download(context.Background(), url, opts)
if result.Resumed {
    fmt.Println("Download resumed from previous position")
}
Download with Context

Download accepts a context.Context directly, so cancellation and timeouts apply out of the box — there is no separate "WithContext" entry point:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()

result, _ := httpc.Download(ctx,
    "https://example.com/large.zip",
    &httpc.DownloadConfig{FilePath: "downloads/large.zip"},
)

// Full control: download config + context + request options
result, _ := httpc.Download(ctx, url, opts,
    httpc.WithBearerToken("your-token"),
)
DownloadConfig Fields
Field Type Description
FilePath string Destination path for the downloaded file
ProgressCallback DownloadProgressCallback Progress callback: func(downloaded, total int64, speed float64)
Overwrite bool Overwrite existing file (default: false)
ResumeDownload bool Resume interrupted download (default: false)
Checksum string Expected checksum for verification
ChecksumAlgorithm ChecksumAlgorithm Checksum algorithm (e.g., httpc.ChecksumSHA256)
Download Functions
Function Description
Download(ctx, url, cfg, ...options) Canonical entry point — single function for all package-level downloads
DownloadResult Fields
Field Type Description
FilePath string Local file path written to
BytesWritten int64 Total bytes written
Duration time.Duration Download duration
AverageSpeed float64 Average download speed (bytes/sec)
StatusCode int HTTP status code
ContentLength int64 Content-Length from server
Resumed bool Whether download was resumed
ResponseCookies []*http.Cookie Cookies from response
ActualChecksum string Computed checksum of downloaded file
Proto string HTTP protocol version (e.g., "HTTP/1.1", "HTTP/2.0")
ResponseHeaders http.Header Response headers
RequestURL string Actual URL requested
RequestMethod string HTTP method used
RequestHeaders http.Header Request headers sent

Streaming Bodies

For large payloads, HTTPC avoids buffering entire bodies in memory.

Streaming Request Body (Upload)

WithBody accepts io.Reader directly. Content-Type is not auto-detected for readers, so set it explicitly:

// Stream from a file or any io.Reader
result, err := httpc.Post("https://example.com/upload",
    httpc.WithBody(file),
    httpc.WithHeader("Content-Type", "application/octet-stream"),
)

Zero-copy streaming with io.Pipe — the producer goroutine writes while the HTTP transport consumes concurrently:

pr, pw := io.Pipe()
go func() {
    defer pw.Close()
    // Write chunks to pw ...
}()

result, err := httpc.Post("https://example.com/upload",
    httpc.WithBody(pr),
    httpc.WithHeader("Content-Type", "application/octet-stream"),
)

Security: WithBody(io.Reader) bypasses request-body-size validation. Wrap untrusted readers with io.LimitReader to enforce a cap:

httpc.WithBody(io.LimitReader(reader, 10<<20)) // 10 MB cap
Streaming Response Body (Download)

Download() streams the response body directly to disk — it never buffers the full body. WithStreamBody(true) is applied automatically:

result, _ := httpc.Download(ctx,
    "https://example.com/large.zip",
    &httpc.DownloadConfig{FilePath: "downloads/large.zip"},
)

Note: Regular Get / Post / etc. always buffer the full response body into memory. Passing WithStreamBody(true) to these methods returns ErrStreamBodyRequiresDownload — use Download for large responses. See File Download for details.


Domain Client (Session Management)

For multiple requests to the same domain with automatic cookie and header management:

client, _ := httpc.NewDomainDefault("https://api.example.com")
defer client.Close()

// Login - server sets cookies
client.Post("/login", httpc.WithJSON(credentials))

// Set persistent header (used for all requests)
client.SetHeader("Authorization", "Bearer "+token)

// Subsequent requests include cookies + headers automatically
profile, _ := client.Get("/profile")
data, _ := client.Get("/data")
// Single cookie
client.SetCookie(&http.Cookie{Name: "session", Value: "abc"})

// Multiple cookies
client.SetCookies([]*http.Cookie{
    {Name: "session", Value: "abc"},
    {Name: "token", Value: "xyz"},
})

// Read cookies
cookie := client.GetCookie("session")   // Single cookie
allCookies := client.GetCookies()        // All cookies

// Remove cookies
client.DeleteCookie("session")
client.ClearCookies()
Header Management
client.SetHeader("X-Custom", "value")
client.SetHeaders(map[string]string{"X-App": "v1", "X-Version": "1.0"})
headers := client.GetHeaders()
client.DeleteHeader("X-Old")
client.ClearHeaders()
Accessors
client.URL()     // Full base URL
client.Domain()  // Domain only
client.Session() // Underlying SessionManager
File Downloads (relative paths)
result, _ := client.Download(ctx, "/files/data.csv", &httpc.DownloadConfig{FilePath: "data.csv"})
result, _ := client.Download(ctx, "/files/large.zip", downloadOpts)
All HTTP Methods
result, _ := client.Get("/users")
result, _ := client.Post("/users", httpc.WithJSON(data))
result, _ := client.Put("/users/1", httpc.WithJSON(data))
result, _ := client.Patch("/users/1", httpc.WithJSON(data))
result, _ := client.Delete("/users/1")
result, _ := client.Head("/users")
result, _ := client.Options("/users")
result, _ := client.Request(ctx, "PROPFIND", "/resource")

Session Manager

The SessionManager provides thread-safe cookie and header management, used internally by DomainClient but also available standalone:

// Create session manager
sm, _ := httpc.NewSessionManagerDefault()

// Or with cookie security validation
cfg := httpc.DefaultSessionConfig()
cfg.CookieSecurity = httpc.StrictCookieSecurityConfig()
sm, _ := httpc.NewSessionManager(cfg)

// Manage cookies
sm.SetCookie(&http.Cookie{Name: "session", Value: "abc"})
sm.SetCookies([]*http.Cookie{{Name: "token", Value: "xyz"}})
cookie := sm.GetCookie("session")
allCookies := sm.GetCookies()
sm.DeleteCookie("session")
sm.ClearCookies()

// Manage headers
sm.SetHeader("Authorization", "Bearer token")
sm.SetHeaders(map[string]string{"X-App": "v1"})
headers := sm.GetHeaders()
sm.DeleteHeader("X-Old")
sm.ClearHeaders()

// Update from response
sm.UpdateFromResult(result)
sm.UpdateFromCookies(responseCookies)

// Cookie security
sm.SetCookieSecurity(httpc.StrictCookieSecurityConfig())

Configuration

Preset Configurations
// Recommended defaults
client, _ := httpc.NewDefault()

// Maximum security (SSRF protection enabled)
client, _ := httpc.New(httpc.SecureConfig())

// High throughput
client, _ := httpc.New(httpc.PerformanceConfig())

// Lightweight (no retries)
client, _ := httpc.New(httpc.MinimalConfig())

// Testing only - disables security features!
client, _ := httpc.New(httpc.TestingConfig())
Custom Configuration
config := httpc.Config{
    // Timeouts
    Timeouts: httpc.TimeoutConfig{
        Request:        30 * time.Second,
        Dial:           10 * time.Second,
        TLSHandshake:   10 * time.Second,
        ResponseHeader: 0, // disabled: rely on the context timeout (set a positive value only for a hard transport-level cap)
        IdleConn:       90 * time.Second,
    },

    // Connection
    Connection: httpc.ConnectionConfig{
        MaxIdleConns:    100,
        MaxConnsPerHost: 20,
        EnableHTTP2:     true,
        EnableCookies:   false,
    },

    // Security
    Security: httpc.SecurityConfig{
        MinTLSVersion:       tls.VersionTLS12,
        MaxTLSVersion:       tls.VersionTLS13,
        MaxResponseBodySize: 50 * 1024 * 1024, // 50 MB
        AllowPrivateIPs:     false,
        FollowRedirects:     true,
        MaxRedirects:        10,
    },

    // Retry
    Retry: httpc.RetryConfig{
        MaxRetries:    3,
        Delay:         1 * time.Second,
        BackoffFactor: 2.0,
        EnableJitter:  true,
    },

    // Defaults (per-request defaults: User-Agent, headers)
    Defaults: httpc.RequestDefaults{
        UserAgent: "MyApp/1.0",
    },
}

// Validate configuration before creating client (New() also validates internally)
if err := config.Validate(); err != nil {
    log.Fatal(err)
}

client, _ := httpc.New(config)

// Inspect configuration (sensitive values are automatically masked)
fmt.Println(config.String())
Configuration Options
Function Description
DefaultConfig() Recommended defaults
SecureConfig() Maximum security (SSRF protection enabled)
PerformanceConfig() High throughput
MinimalConfig() Lightweight (no retries)
TestingConfig() Testing only - disables security features
Config.Validate() Validate configuration, returns error (function form: ValidateConfig(cfg))
Config.String() Safe string representation (sensitive values masked)
Option Type Default Description
Timeouts (Timeouts: httpc.TimeoutConfig{...})
Timeouts.Request time.Duration 180s Overall request timeout
Timeouts.Dial time.Duration 10s TCP connection timeout
Timeouts.TLSHandshake time.Duration 10s TLS handshake timeout
Timeouts.ResponseHeader time.Duration 0 Response header timeout (0 = disabled, uses context timeout)
Timeouts.IdleConn time.Duration 90s Idle connection timeout
Connection (Connection: httpc.ConnectionConfig{...})
Connection.MaxIdleConns int 50 Max idle connections
Connection.MaxConnsPerHost int 10 Max connections per host
Connection.ProxyURL string "" Proxy URL (http/https/socks5/socks5h)
Connection.EnableSystemProxy bool false Auto-detect system proxy
Connection.ProxyPool []string nil Proxy URLs for rotation (see Proxy Configuration)
Connection.ProxyPoolStrategy ProxyStrategy ProxyStrategyRoundRobin Proxy selection algorithm (ProxyStrategyRoundRobin or ProxyStrategyRandom)
Connection.ProxyFailureThreshold int 3 Consecutive connection failures before circuit-breaking a proxy
Connection.ProxyCooldown time.Duration 30s How long a circuit-broken proxy stays out of rotation
Connection.ProxyRotateOnStatus []int nil HTTP status codes that trigger proxy rotation (e.g., []int{403})
Connection.ProxyRotatePerRequest bool false Close idle connections before each request so the transport re-evaluates the proxy pool, guaranteeing per-request rotation (adds overhead: no connection reuse). Requires ProxyPool; no effect with ProxyURL
Connection.EnableHTTP2 bool true Enable HTTP/2
Connection.EnableCookies bool false Enable cookie jar
Connection.EnableDoH bool false Enable DNS-over-HTTPS
Connection.DoHCacheTTL time.Duration 5m DoH cache duration
Connection.MaxResponseHeaderBytes int64 0 Max response header size (0 = Go stdlib default 1MB)
Connection.PublicSuffixList cookiejar.PublicSuffixList nil Public-suffix database for the cookie jar (recommended: golang.org/x/net/publicsuffix.List)
Security (Security: httpc.SecurityConfig{...})
Security.TLSConfig *tls.Config nil Custom TLS config
Security.MinTLSVersion uint16 TLS 1.2 Minimum TLS version
Security.MaxTLSVersion uint16 TLS 1.3 Maximum TLS version
Security.InsecureSkipVerify bool false Skip TLS verification (testing only!)
Security.TLSFingerprint string "" Browser fingerprint preset — see Browser Transport Fingerprinting
Security.TLSFingerprintDisableSessionTickets bool false Force a full TLS handshake on every fingerprinted connection (Chrome profiles resume sessions by default)
Security.CertificatePinner CertificatePinner nil Certificate pinning — reject MITM even if CA compromised (works with TLSFingerprint)
Security.MaxResponseBodySize int64 10MB Max response body size
Security.MaxRequestBodySize int64 0 Max request body size (0 = no limit; does not fall back to MaxResponseBodySize). io.Reader bodies are enforced at send time
Security.AllowPrivateIPs bool false Allow private IPs (SSRF protection enabled by default)
Security.ValidateURL bool true Enable URL validation
Security.ValidateHeaders bool true Enable header validation
Security.StrictContentLength bool true Strict content-length check
Security.RedirectWhitelist []string nil Allowed redirect domains
Security.MaxDecompressedBodySize int64 100MB Max decompressed body size (zip bomb protection)
Security.SSRFExemptCIDRs []string nil CIDR ranges exempted from SSRF blocking
Security.FollowRedirects bool true Follow redirects
Security.MaxRedirects int 10 Redirect limit; counts the initial request, so 10 follows at most 9 redirects
Security.SensitiveHeaders []string nil Extra header names stripped on cross-origin redirects (Authorization/Cookie are always stripped)
Retry (Retry: httpc.RetryConfig{...})
Retry.MaxRetries int 3 Max retry attempts
Retry.Delay time.Duration 1s Initial retry delay
Retry.BackoffFactor float64 2.0 Backoff multiplier
Retry.EnableJitter bool true Add jitter to retries
Retry.MaxRetryDelay time.Duration 30s Cap on maximum retry delay
Retry.CustomPolicy RetryPolicy nil Custom retry logic
Retry.RetryNonIdempotent bool false Retry non-idempotent methods (POST/PATCH); off by default — they execute exactly once
Middleware (Middleware: httpc.MiddlewareConfig{...})
Middleware.Middlewares []MiddlewareFunc nil Middleware chain
Defaults (Defaults: httpc.RequestDefaults{...})
Defaults.UserAgent string "httpc/1.0" Default User-Agent
Defaults.Headers map[string]string {} Default headers

Middleware

Every configurable middleware follows the same pattern: a XxxConfig struct, a DefaultXxxConfig() constructor, and a XxxMiddleware(cfg) factory. Pass nil to accept defaults.

Built-in Middleware
// Request logging
httpc.LoggingMiddleware(&httpc.LoggingConfig{LogFunc: log.Printf})

// Panic recovery (no config needed)
httpc.RecoveryMiddleware()

// Request ID (nil config = defaults: "X-Request-ID" header, crypto/rand generator)
httpc.RequestIDMiddleware(&httpc.RequestIDConfig{HeaderName: "X-Request-ID"})

// Timeout enforcement
httpc.TimeoutMiddleware(&httpc.TimeoutMiddlewareConfig{Duration: 30 * time.Second})

// Static headers
httpc.HeaderMiddleware(&httpc.HeaderConfig{
    Headers: map[string]string{"X-App-Version": "1.0.0"},
})

// Metrics collection
httpc.MetricsMiddleware(&httpc.MetricsConfig{
    OnMetrics: func(method, url string, statusCode int, duration time.Duration, err error) {
        metrics.Record(method, url, statusCode, duration)
    },
})

// Security audit
auditCfg := httpc.DefaultAuditConfig()
auditCfg.OnAudit = func(a httpc.AuditEvent) {
    log.Printf("[AUDIT] %s %s -> %d (%v)", a.Method, a.URL, a.StatusCode, a.Duration)
}
httpc.AuditMiddleware(auditCfg)

// Audit with custom config (include request/response headers in the event)
auditCfgJSON := httpc.DefaultAuditConfig()
auditCfgJSON.OnAudit = func(a httpc.AuditEvent) { log.Printf("[AUDIT] %v", a) }
auditCfgJSON.IncludeHeaders = true
httpc.AuditMiddleware(auditCfgJSON)
AuditEvent Fields
Field Type Description
Timestamp time.Time Request timestamp
Method string HTTP method
URL string Request URL
StatusCode int Response status code
Duration time.Duration Request duration
Attempts int Retry attempts
Error error Error if any
SourceIP string Source IP (set via context key SourceIPKey)
UserID string User ID (set via context key UserIDKey)
RedirectChain []string Redirect URLs
ReqHeaders map[string][]string Request headers (when IncludeHeaders: true)
RespHeaders map[string][]string Response headers (when IncludeHeaders: true)

AuditEvent supports JSON serialization via MarshalJSON().

Chain Multiple Middleware
chainedMiddleware := httpc.Chain(
    httpc.RecoveryMiddleware(),
    httpc.LoggingMiddleware(&httpc.LoggingConfig{LogFunc: log.Printf}),
    httpc.RequestIDMiddleware(nil),
    httpc.HeaderMiddleware(&httpc.HeaderConfig{Headers: map[string]string{"X-App": "v1"}}),
)
config.Middleware.Middlewares = []httpc.MiddlewareFunc{chainedMiddleware}
Custom Middleware
func CustomMiddleware() httpc.MiddlewareFunc {
    return func(next httpc.Handler) httpc.Handler {
        return func(ctx context.Context, req httpc.RequestMutator) (httpc.ResponseMutator, error) {
            // Before request
            req.SetHeader("X-Custom", "value")

            // Call next handler
            resp, err := next(ctx, req)

            // After response
            return resp, err
        }
    }
}

Proxy Configuration

// Manual proxy
config := httpc.DefaultConfig()
config.Connection.ProxyURL = "http://127.0.0.1:8080"
// Or HTTPS proxy: "https://proxy.example.com:8443"

// System proxy auto-detection (Windows/macOS/Linux)
config := httpc.DefaultConfig()
config.Connection.EnableSystemProxy = true // Reads from environment and system settings
Proxy Pool (Rotation + Circuit Breaking)

Distribute requests across multiple proxies with automatic failover and status-based rotation:

config := httpc.DefaultConfig()
config.Connection.ProxyPool = []string{
    "http://proxy1.example.com:7070",
    "http://proxy2.example.com:8080",
    "socks5://proxy3.example.com:1080",
}
// Strategy: ProxyStrategyRoundRobin (default) or ProxyStrategyRandom
config.Connection.ProxyPoolStrategy = httpc.ProxyStrategyRoundRobin

// Circuit breaking: after 5 consecutive connection failures, skip the proxy
// for 60s, then retry it (half-open probe). Defaults: threshold=3, cooldown=30s.
config.Connection.ProxyFailureThreshold = 5
config.Connection.ProxyCooldown = 60 * time.Second

// Rotate proxy on 403 (CF/WAF IP blocking). The request is retried
// through a different proxy IP. Requires Retry.MaxRetries > 0.
// Unlike connection failures, status-based rotation does NOT circuit-break
// the proxy — blocks are often target-specific.
config.Connection.ProxyRotateOnStatus = []int{403}
config.Retry.MaxRetries = 3
Per-Request Proxy Rotation

By default, HTTP connection reuse causes consecutive requests to the same host to reuse the previous proxy tunnel, bypassing pool selection. Enable ProxyRotatePerRequest to guarantee each independent Get/Post call routes through a different proxy:

config.Connection.ProxyRotatePerRequest = true

This closes idle connections at the start of each request so the transport re-evaluates the proxy pool. It adds a small overhead (no connection reuse) but is essential for scraping or fingerprint-rotation use cases. Requires ProxyPool; has no effect with ProxyURL.

Which Proxy Served a Request?

Every Result reports the proxy that produced its final response, so rotation can be verified or logged per request (empty string means a direct connection):

result, _ := client.Get("https://httpbin.org/ip")
fmt.Println(result.Meta.ProxyURL) // e.g. "http://proxy2.example.com:8080"

With retries each attempt may use a different proxy; ProxyURL reflects the attempt that returned the response (Meta.Attempts holds the count).

Priority: ProxyURL > ProxyPool > EnableSystemProxy > direct.


Security Features

Feature Description
TLS 1.2+ Modern encryption standards by default
Certificate Pinning Defense against MITM even with a compromised CA
SSRF Protection Two-layer DNS validation blocks private IPs
CRLF Injection Prevention Header and URL validation
Path Traversal Protection Safe file operations
Domain Whitelist Restrict redirects to allowed domains
Response Size Limit Configurable limit to prevent memory exhaustion
Redirect Domain Whitelist
config := httpc.DefaultConfig()
config.Security.RedirectWhitelist = []string{"api.example.com", "secure.example.com"}
SSRF Protection

By default, AllowPrivateIPs is false (SSRF protection enabled), blocking connections to private/reserved IP addresses. Set to true only when connecting to internal services:

// SSRF protection is enabled by default
client, _ := httpc.New(httpc.DefaultConfig())

// Allow private IPs for internal service access
cfg := httpc.DefaultConfig()
cfg.Security.AllowPrivateIPs = true
client, _ := httpc.New(cfg)

// Or exempt specific CIDRs (e.g., VPN/VPC ranges)
cfg := httpc.DefaultConfig()
cfg.Security.SSRFExemptCIDRs = []string{"10.0.0.0/8", "100.64.0.0/10"}
client, _ := httpc.New(cfg)

For a single trusted internal call without relaxing the whole client, use the per-request WithAllowPrivateIPs option (it overrides the client's SSRF policy for that one request only):

// Default client blocks private IPs; this call opts in for one request
result, err := httpc.Get("http://localhost:8080/health",
    httpc.WithAllowPrivateIPs(true),
)
SSRF Protection Through a Proxy

When a proxy is configured (Connection.ProxyURL, Connection.ProxyPool, or Connection.EnableSystemProxy), the proxy resolves the target hostname remotely instead of this process, so the connection-layer check cannot see what the proxy will dial. To keep SSRF protection intact on the proxied path, httpc resolves and validates the target hostname locally before the proxy carries the request, and rejects it when every resolved address is blocked (private/reserved/link-local). This guard runs only while Security.AllowPrivateIPs is false (the default), and honors the per-request WithAllowPrivateIPs override.

Two consequences to be aware of when proxying:

  • Fail-closed on local DNS. A hostname this process cannot resolve is rejected even if the proxy could resolve it — with SSRF protection on, the only safe answer is to refuse. Reach intranet-only hostnames through Security.SSRFExemptCIDRs (which exempts the resolved private IPs), or opt out of the guard with AllowPrivateIPs: true.
  • No DNS-rebinding guarantee on this path. The proxy still performs its own second resolution for the actual dial, so the direct path's resolve-once-and-dial-the-validated-IP rebinding defense does not extend to proxied requests. The guard closes the deterministic hostname→private-IP bypass; a rebinding-hardened proxy would require the proxy itself to honor pinned IPs.
cfg := httpc.DefaultConfig()
cfg.Connection.ProxyURL = "http://127.0.0.1:8080" // SSRF guard still enforced
// cfg.Security.AllowPrivateIPs = false            // default: guard active

// Intranet host reachable only through the proxy:
cfg.Security.SSRFExemptCIDRs = []string{"10.0.0.0/8"} // exempts 10.x targets
Certificate Pinning

Certificate pinning defends against man-in-the-middle attacks even when a trusted Certificate Authority is compromised: the TLS handshake is rejected unless the server presents a pinned public key. Enable it by assigning a CertificatePinner to Security.CertificatePinner.

// Pin by base64-encoded SHA-256 hash of the SubjectPublicKeyInfo (SPKI).
// Supply multiple hashes to support key rotation (accept if ANY matches).
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)

Certificate pinning also works on the fingerprint path (Security.TLSFingerprint): the pinner runs as the spoofed handshake's VerifyPeerCertificate hook. With InsecureSkipVerify set, the pinner becomes the only verification gate and pins the leaf certificate (verified chains are unavailable when verification is skipped).

Generate an SPKI hash from a certificate:

openssl x509 -in cert.pem -pubkey -noout | openssl pkey -pubin -outform der \
  | openssl dgst -sha256 -binary | openssl enc -base64
Function Description
NewSPKIHashPinner(hashes ...string) Pin by base64 SHA-256 SPKI hashes (recommended; HPKP format)
NewPublicKeyPinner(publicKeys ...[]byte) Pin by DER-encoded PKIX public keys
NewCertificatePinnerChain(pinners ...CertificatePinner) Combine multiple pinners (accept if ANY matches)
Security Warning Output

By default, security warnings are printed to stderr when using insecure configurations (e.g., TestingConfig(), InsecureSkipVerify: true). Redirect or suppress these warnings:

// Suppress security warnings (e.g., in CI environments)
httpc.SetSecurityWarnOutput(io.Discard)

// Or redirect to a custom logger
httpc.SetSecurityWarnOutput(os.Stderr)

Browser Transport Fingerprinting

Modern WAFs (Cloudflare, Akamai, DataDome) fingerprint more than the User-Agent: the TLS ClientHello (JA3/JA4), the HTTP/2 frames (SETTINGS values and order, WINDOW_UPDATE, pseudo-header order, priorities, HPACK behavior), and the header block itself — including a User-Agent coherent with the ClientHello version. Setting Security.TLSFingerprint replaces httpc's transport layer with a browser emulation covering all of them at once, over fully fingerprinted HTTP/2 (preferred) and HTTP/1.1 (fallback):

cfg := httpc.DefaultConfig()
cfg.Security.TLSFingerprint = "chrome-latest" // or "chrome-windows", "firefox-latest", ...
client, err := httpc.New(cfg)

Everything above the transport stays in charge: redirects, retries, middleware, streaming downloads, and cookie handling keep their httpc semantics.

Scope: fingerprinting makes the transport layers — TLS, HTTP/2 framing, ordered header block — indistinguishable from the spoofed browser, which defeats passive fingerprinting (JA3/JA4, the Akamai H2 fingerprint, header order). It does not defeat — no pure HTTP client can — defenses that execute JavaScript (Cloudflare Managed Challenge / Turnstile, DataDome, Akamai sensor), behavioral scoring, or IP reputation; those call for a real browser or an authorized challenge-solving step. Profiles are snapshots of one browser build and age as browsers ship: internal/fingerprint/PROFILES.md documents the update runbook, and a weekly CI job watches for drift (.github/workflows/fingerprint-drift.yml).

Preset names are browser profiles with optional OS suffixes: chrome / chrome-latest / chrome-155 (= Chrome 155) and firefox / firefox-latest / firefox-158 (= Firefox 158), each as *-windows / *-macos / *-linux desktop variants and *-android / *-ios mobile variants (e.g. chrome-windows, firefox-ios), plus the retired-major pins chrome-152 and firefox-148, the legacy compound aliases android-chrome-latest and ios-chrome-latest, and safari-ios (= ios-safari-latest) — Safari on the same verified WebKit data as the other iOS presets. There is no desktop-Safari profile: macOS Safari's ClientHello differs and no verified data for it exists yet.

Behavior notes:

  • Header set is authoritative: the preset replaces same-named request headers (User-Agent, Accept, Accept-Language, ...) with the browser profile's values so the wire stays coherent with the spoofed ClientHello; custom headers pass through untouched. An explicitly set User-Agent does not override the preset on this path. Names are written with the browser's own casing — lower-case sec-ch-ua*, Title-Case everything else — on HTTP/1.1 as well as HTTP/2.
  • Protocols: ALPN decides. A server that speaks HTTP/2 gets HTTP/2, one that only speaks HTTP/1.1 gets HTTP/1.1, and no request is ever replayed: there is no manual fallback between the two. HTTP/3 is never attempted — a QUIC connection uses a separate TLS stack that bypasses CertificatePinner, and losing the pin silently is worse than not racing protocols. Connection.EnableHTTP2=false pins the path to HTTP/1.1 and rewrites the ClientHello's ALPN list to match.
  • Proxies: proxy pools, rotation, and circuit breaking keep working (HTTP, HTTPS and SOCKS5/5h). Plain-HTTP targets through an HTTP proxy traverse a CONNECT tunnel; HTTPS proxies speak HTTP/1.1 CONNECT only and their certificate is verified against the system roots and the proxy hostname (set Security.InsecureSkipVerify to opt out, exactly as on the standard transport). The proxy is fixed per connection pool — rotation selects a different pool rather than re-pointing a live one.
  • Redirect coherence: on every redirect hop the profile's first-hop values are corrected the way a browser does: sec-fetch-site is recomputed against the previous hop's URL (same-origin / same-site / cross-site), sec-fetch-user is dropped (first hop only), and a 301/302/303 that downgrades a fetch-style request to GET keeps fetch-style headers instead of switching to navigation headers.
  • Certificate pinning works: CertificatePinner runs on every fingerprinted handshake (see the pinning section above). Security.TLSConfig remains mutually exclusive with fingerprinting (a custom tls.Config cannot shape a spoofed ClientHello).
  • Decompression: the profile advertises gzip, deflate, br, zstd and the fingerprint stack decodes all of them (streaming preserved), handing the engine identity bodies — the engine cannot see the original Content-Encoding, so the decoded stream is capped by MaxResponseBodySize (MaxDecompressedBodySize does not apply on this path). An unknown Content-Encoding fails the request loudly instead of returning compressed bytes.
  • SSRF protection runs as a resolve-and-validate pre-flight per request (including each redirect hop); it is marginally weaker than the standard path's dial-layer validation (theoretical DNS TOCTOU window).
  • Limitations: fingerprinted connections are not counted in pool metrics and skip Connection.EnableDoH. Android presets (*-android) currently emit the desktop fingerprint bytes — placeholders pending real device captures (see internal/fingerprint/PROFILES.md). iOS presets (*-ios, including safari-ios) use real WebKit data (Safari 26.3 TLS + HTTP/2, byte-verified live), with the regular-header order still a desktop approximation.
  • Session resumption: the Chrome profiles cache TLS session tickets per connection pool and resume repeat connections with a PSK, exactly like a real browser revisiting a host (verified live in session_resumption_test.go). Profiles whose ClientHello carries no pre_shared_key extension (Firefox, the iOS WebKit profiles) always full-handshake. Set Security.TLSFingerprintDisableSessionTickets to force a full handshake on every connection.
  • Verified end-to-end: chrome-latest negotiates h2 with the Chrome Akamai fingerprint 1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p (hash 52d84b11737d980aef856699f885ca86) and a Chrome 155 UA; firefox-latest yields 1:65536;2:0;4:131072;5:16384|12517377|0|m,p,a,s (hash 6ea73faa8fc5aac76bded7bd238f6433) with a Firefox 158 UA; chrome-ios and safari-ios yield the WebKit JA4 t13d2013h2_a09f3c656075_7f0f34a4126d with Akamai 2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p (hash c52879e43202aeb92740be6e8c86ea96) — see internal/fingerprint/e2e_network_test.go (go test -tags fingerprint_e2e ./internal/fingerprint/ -run PeetWSE2E).

The fingerprint data lives in this repository (internal/fingerprint): httpc builds the ClientHello spec, the HTTP/2 SETTINGS sequence and the header tables, and hands them to bogdanfinn/tls-client through its profile API — so a profile can target a browser build ahead of any upstream release. The transport itself (uTLS handshake, HTTP/2 framing, header order and casing) comes from that library, and andybalholm/brotli + klauspost/compress (zstd) handle decoding. Profile data was originally ported from enetx/surf (MIT); httpc does not depend on that client library, nor on enetx/http, enetx/http2 or refraction-networking/utls. Leave TLSFingerprint empty to keep the standard stack with no extra dependencies.


Error Handling

result, err := httpc.Get(url)
if err != nil {
    var clientErr *httpc.ClientError
    if errors.As(err, &clientErr) {
        fmt.Printf("Error: %s (code: %s)\n", clientErr.Message, clientErr.Code())
        fmt.Printf("Retryable: %v\n", clientErr.IsRetryable())
    }
    return err
}

// Check response status
if !result.IsSuccess() {
    return fmt.Errorf("unexpected status code: %d", result.StatusCode())
}
ClientError Fields
Field Type Description
Type ErrorType Error classification
Message string Human-readable error description
Cause error Underlying error (unwrap with %w)
URL string Request URL
Method string HTTP method
Attempts int Total attempts made, including the first
StatusCode int HTTP status code (if applicable)
Host string Reserved; currently never set by the engine
Error Types
const (
    ErrorTypeUnknown        // Unknown or unclassified error
    ErrorTypeNetwork        // Network-level error (connection refused, DNS failure)
    ErrorTypeTimeout        // Request timeout
    ErrorTypeContextCanceled // Context canceled
    ErrorTypeResponseRead   // Error reading response body
    ErrorTypeTransport      // HTTP transport error
    ErrorTypeRetryExhausted // Reserved for retry exhaustion; retries actually exhaust with the last error's type kept — check Attempts / IsRetryable()
    ErrorTypeTLS            // TLS handshake error
    ErrorTypeCertificate    // Certificate validation error
    ErrorTypeDNS            // DNS resolution error
    ErrorTypeValidation     // Request validation error
    ErrorTypeHTTP           // HTTP-level error (4xx, 5xx)
)
Sentinel Errors
var (
    ErrClientClosed         // Client has been closed
    ErrNilConfig            // Nil configuration provided
    ErrInvalidHeader        // Header validation failed
    ErrInvalidTimeout       // Timeout is negative or exceeds limits
    ErrInvalidRetry         // Retry configuration is invalid
    ErrInvalidConnection    // Connection configuration is invalid
    ErrInvalidSecurity      // Security configuration is invalid
    ErrInvalidMiddleware    // Middleware configuration is invalid
    ErrEmptyFilePath        // File path is empty
    ErrFileExists           // File already exists (and Overwrite is false)
    ErrResponseBodyEmpty    // Response body is empty
    ErrResponseBodyTooLarge // Response body exceeds size limit
    ErrInvalidMaxRedirects  // Redirect limit is negative or exceeds 50
    ErrInvalidCredentials   // Basic/Bearer credentials failed validation
    ErrStreamBodyRequiresDownload // WithStreamBody used with a buffered method (use Download)
    ErrDownloadInProgress   // A download to the same path is already running
    ErrProxyConnectionFailed // A configured proxy could not be dialed
)
Error Classification
// Check error type using errors.As
var clientErr *httpc.ClientError
if errors.As(err, &clientErr) {
    fmt.Printf("Type: %s, Retryable: %v\n", clientErr.Code(), clientErr.IsRetryable())
}

Concurrency Safety

HTTPC is designed to be goroutine-safe:

client, _ := httpc.NewDefault() // Default configuration
defer client.Close()

var wg sync.WaitGroup
for i := 0; i < 100; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        result, _ := client.Get("https://api.example.com")
        // Process response...
    }()
}
wg.Wait()
Default Client Management

Package-level functions (Get, Post, etc.) use a shared default client. You can customize it:

// Set a custom default client
customClient, _ := httpc.New(httpc.SecureConfig())
_ = httpc.SetDefaultClient(customClient)

// Close and reset the default client
_ = httpc.CloseDefaultClient()

Thread Safety Guarantees:

  • All Client methods are safe for concurrent use
  • Package-level functions safely use a shared default client
  • Result objects are immutable once returned — concurrent reads are safe; just avoid multiple goroutines assigning to the same Result variable
  • Internal metrics use atomic operations

Interfaces

HTTPC exposes interfaces for testing and extensibility. Use these when you need to mock HTTP calls in your tests:

Doer

The simplest interface — a single Request method:

type Doer interface {
    Request(ctx context.Context, method, url string, options ...RequestOption) (*Result, error)
}
Client

The full client interface — extends Doer with convenience methods and download support:

type Client interface {
    Doer
    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(ctx context.Context, url string, cfg *DownloadConfig, options ...RequestOption) (*DownloadResult, error)
    Close() error
}
DomainClienter

Extends Client with domain-scoped session management:

type DomainClienter interface {
    Client
    URL() string
    Domain() string
    SetHeader(key, value string) error
    SetHeaders(headers map[string]string) error
    DeleteHeader(key string)
    ClearHeaders()
    GetHeaders() map[string]string
    SetCookie(cookie *http.Cookie) error
    SetCookies(cookies []*http.Cookie) error
    DeleteCookie(name string)
    ClearCookies()
    GetCookies() []*http.Cookie
    GetCookie(name string) *http.Cookie
    Session() *SessionManager
}
Usage in Tests
type MockClient struct {
    httpc.Client // embed for forward compatibility
}

func (m *MockClient) Get(url string, options ...httpc.RequestOption) (*httpc.Result, error) {
    return &httpc.Result{
        Response: &httpc.ResponseInfo{StatusCode: 200, Body: `{"ok": true}`},
    }, nil
}

Documentation

Resource Description
Getting Started Installation and first steps
Configuration Client configuration and presets
Request Options Complete options reference
Error Handling Error handling patterns
HTTP Redirects Redirect handling and tracking
Cookie API Cookie management
File Download File download with progress
Request Inspection Request/response inspection
Concurrency Safety Thread safety guarantees
Security Security features and best practices
Example Code

23 runnable examples covering all features, ordered from basic to advanced. Each example is a standalone package main guarded by a //go:build examples tag (so it stays out of the normal build), so run them one at a time:

go run -tags examples examples/01_basic_usage.go

Examples that call live endpoints (httpbin.org, example.com) require network access. The certificate-pinning and SSRF-protection examples are self-contained — a rejection is the protection working as designed.

Category Examples
Basics 01_basic_usage, 02_http_methods, 03_response_handling, 04_compression
Core Features 05_request_options, 06_error_handling, 07_timeout_retry, 08_client_configuration, 09_redirects, 10_cookies_advanced
Stateful Clients 11_session, 12_domain_client, 13_proxy_configuration, 14_doh
Advanced 15_middleware, 16_concurrent_requests, 17_file_operations, 18_rest_api_client, 19_advanced_patterns
Security 20_certificate_pinning, 21_ssrf_protection
Streaming 22_streaming_bodies
Fingerprinting 23_tls_fingerprint

License

MIT License - see LICENSE file for details.


If this project helps you, please give it a Star!

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; non-idempotent requests (POST/PATCH) execute exactly once by default
  • 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.
  • Middleware config types are named XxxConfig paired with DefaultXxxConfig(); TimeoutMiddlewareConfig is the lone exception, carrying the Middleware suffix to avoid colliding with the client-level TimeoutConfig (Config.Timeouts).
  • 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.WithCookies([]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.WithNoTimeout() // lift the client default for one slow call
httpc.WithMaxRetries(3)
httpc.WithRetryNonIdempotent(true) // opt in to POST retries (replay-safe endpoints only)
httpc.WithFollowRedirects(false)
httpc.WithMaxRedirects(5)
httpc.WithStreamBody(true) // Download only; errors on Get/Post/...

// 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 and default headers — live on Config.Defaults (RequestDefaults), populated by DefaultConfig(). Redirect policy lives on Config.Security (FollowRedirects, MaxRedirects, RedirectWhitelist):

cfg := httpc.DefaultConfig()
cfg.Defaults.UserAgent = "myapp/2.0"
cfg.Security.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

View Source
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"
)
View Source
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

View Source
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")

	// ErrInvalidMaxRedirects is returned when a redirect limit is invalid —
	// the per-request limit (WithMaxRedirects) is negative or exceeds 50, or
	// the config-level Security.MaxRedirects is negative or exceeds 50.
	ErrInvalidMaxRedirects = errors.New("invalid max redirects")

	// ErrInvalidCredentials is returned when Basic or Bearer credentials fail
	// validation (empty, oversized, or containing invalid characters).
	ErrInvalidCredentials = errors.New("invalid credentials")

	// 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.
	// Defaults.UserAgent must not exceed the length limit and must not contain
	// control characters.
	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")

	// ErrStreamBodyRequiresDownload is returned when WithStreamBody is used
	// with the standard request methods (Get, Post, ..., Request). Streaming
	// is only effective through Download, which consumes the raw body reader
	// directly; every other path buffers the body into a Result and closes
	// the stream, so the option is rejected instead of silently returning an
	// empty body. Use errors.Is(err, httpc.ErrStreamBodyRequiresDownload) to
	// detect this condition.
	ErrStreamBodyRequiresDownload = errors.New("WithStreamBody requires Download; standard request methods buffer the response body")

	// ErrDownloadInProgress is returned when a Download targeting the same
	// file path is already running in this process. Two concurrent downloads
	// to one destination would corrupt each other's writes (shared temp file
	// or concurrent append), so the second caller fails fast instead of
	// blocking; retry when the first download finishes. The lock is
	// in-process only — coordinating downloads across separate processes is
	// the caller's responsibility.
	ErrDownloadInProgress = errors.New("download already in progress for this file path")

	// ErrProxyConnectionFailed is returned when a configured proxy could not
	// be dialed. It is wrapped (alongside the underlying cause) in every
	// proxy dial failure so callers can detect the condition with
	// errors.Is(err, httpc.ErrProxyConnectionFailed) without matching the
	// specific transport error.
	ErrProxyConnectionFailed = connection.ErrProxyConnectionFailed
)

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

func FormatBytes(bytes int64) string

FormatBytes formats a byte count as a human-readable string (e.g., "1.50 MB").

func FormatSpeed

func FormatSpeed(bytesPerSecond float64) string

FormatSpeed formats a byte-per-second rate as a human-readable string (e.g., "1.50 MB/s").

func SetDefaultClient

func SetDefaultClient(client Client) error

SetDefaultClient sets a custom client as the default for package-level functions. The previous default client is closed automatically. The new client is installed even when closing the previous one fails; in that case the returned error reports the close failure, not a failed swap.

Concurrency: closing the previous default aborts any requests still in flight on it — goroutines that already resolved the old client may observe connection errors. Swap the default only at startup or during a quiescent window, never under live traffic. 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

func SetSecurityWarnOutput(w io.Writer)

SetSecurityWarnOutput redirects security warnings (e.g., TestingConfig, InsecureSkipVerify) to the specified writer. Pass io.Discard to suppress all warnings. A nil writer is normalized to io.Discard — storing nil would make the next New() panic inside fmt.Fprintf far from the misconfigured call site.

func ValidateConfig added in v1.1.0

func ValidateConfig(cfg *Config) error

ValidateConfig validates the configuration and returns an error if invalid. This is called internally by New() but can also be called explicitly. Equivalent to (*Config).Validate, which is preferred in new code.

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 is a reserved field with no current effect: audit events are
	// delivered as the structured AuditEvent value via OnAudit, and the
	// rendering (text, JSON, ...) is entirely the callback's choice. Setting
	// "text" or "json" here does nothing.
	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 is when the request started; add Duration for the end time.
	Timestamp time.Time `json:"timestamp"`
	// Method is the HTTP method of the request.
	Method string `json:"method"`
	// URL is the request URL, sanitized (credentials removed).
	URL string `json:"url"`
	// StatusCode is the final HTTP status code (0 when the request errored).
	StatusCode int `json:"statusCode"`
	// Duration covers all attempts, including retry delays; serialized as
	// durationMs by MarshalJSON.
	Duration time.Duration `json:"-"`
	// Attempts is the number of requests sent (1 when no retry occurred;
	// 0 when the request errored before a response arrived).
	Attempts int `json:"attempts"`
	// Error is the request error, if any; marshaled as a string with
	// sensitive details removed.
	Error error `json:"error,omitempty"`
	// SourceIP is an application-supplied caller identifier, if known.
	SourceIP string `json:"sourceIP,omitempty"`
	// UserID is an application-supplied user identifier, if known.
	UserID string `json:"userID,omitempty"`
	// RedirectChain lists the URLs followed before the final response.
	RedirectChain []string `json:"redirectChain,omitempty"`
	// ReqHeaders contains the final request headers (may be nil for early
	// failures).
	ReqHeaders map[string][]string `json:"reqHeaders,omitempty"`
	// RespHeaders contains the final response headers (nil when the request
	// errored before a response arrived).
	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.

TRUST MODEL: pins are matched only against certificates bound to the connection — the leaf and the verified chain. When normal certificate verification runs, a pin may match any certificate in the VERIFIED chain (so CA/intermediate pinning works). When InsecureSkipVerify is enabled (pinning as the sole gate), only the leaf certificate's key is checked — a certificate merely appended to the server's presented chain can never satisfy a pin ("pin stuffing" defense).

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, if a hash is not valid base64, or if it does not decode to exactly 32 bytes (SHA-256).

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

	// Get issues a GET request to url.
	Get(url string, options ...RequestOption) (*Result, error)
	// Post issues a POST request to url (non-idempotent: not retried by default).
	Post(url string, options ...RequestOption) (*Result, error)
	// Put issues a PUT request to url.
	Put(url string, options ...RequestOption) (*Result, error)
	// Patch issues a PATCH request to url (non-idempotent: not retried by default).
	Patch(url string, options ...RequestOption) (*Result, error)
	// Delete issues a DELETE request to url.
	Delete(url string, options ...RequestOption) (*Result, error)
	// Head issues a HEAD request to url.
	Head(url string, options ...RequestOption) (*Result, error)
	// Options issues an OPTIONS request to url.
	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.
	// The download is subject to the client's Security.MaxResponseBodySize
	// (default 10 MB); oversize bodies fail with an error, never a silent
	// truncation — see DownloadConfig.
	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

func New(cfg Config) (Client, error)

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

func NewDefault() (Client, error)

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 configures request, dial, TLS-handshake, response-header, and
	// idle-connection timeouts.
	Timeouts TimeoutConfig
	// Connection configures pooling, proxies, HTTP/2, cookies, and DNS-over-HTTPS.
	Connection ConnectionConfig
	// Security configures TLS, SSRF protection, and body-size limits.
	Security SecurityConfig
	// Retry configures automatic retries of retryable failures.
	Retry RetryConfig
	// Middleware configures the per-client middleware chain.
	Middleware MiddlewareConfig
	// Defaults holds per-request defaults (User-Agent, default headers)
	// applied to every outgoing request. The redirect policy lives on
	// Security, not here.
	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(). New validates the configuration before use; call Validate to pre-check a Config without constructing a client.

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).

NOTE: EnableCookies is set to true with no PublicSuffixList. For sites where cookie leakage across subdomains matters, set cfg.Connection.PublicSuffixList = publicsuffix.List (golang.org/x/net/publicsuffix) before calling New.

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.

func (*Config) String added in v1.3.8

func (c *Config) String() string

String returns a safe string representation of the Config. Sensitive values are masked:

  • ProxyURL credentials (user:pass@host -> ***:***@host)
  • TLSConfig displays as <configured> or <default>
  • Headers are not displayed (may contain sensitive data)

func (*Config) Validate added in v1.6.3

func (c *Config) Validate() error

Validate checks the configuration and returns an error describing the first invalid value found, or nil if the configuration is valid. It is the method form of ValidateConfig, which New and NewDomain call internally; call it directly to validate a Config before construction (e.g., at startup or config-load time).

Calling Validate on a nil *Config is safe and returns ErrNilConfig.

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

	// ProxyRotatePerRequest ensures each independent request (e.g., each
	// Get/Post call) uses a different proxy from the pool. Without this,
	// HTTP connection reuse causes consecutive requests to the same host to
	// reuse the previous request's proxy tunnel, bypassing Proxy() selection.
	//
	// When enabled, idle connections are closed at the start of each request
	// so the transport re-evaluates the proxy pool. This adds a small
	// overhead (no connection reuse) but guarantees per-request rotation.
	//
	// Requires ProxyPool to be set. Has no effect with ProxyURL or when no
	// proxy pool is configured. Default: false.
	ProxyRotatePerRequest bool

	// 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,
	// except that a ProxyPool larger than 1 raises the budget to
	// len(ProxyPool)-1 even from an explicit 0 (see calculateMaxRetries in
	// config_convert.go). Note: the codes become retryable regardless of
	// whether a proxy is configured — with no proxy pool each retry re-hits
	// the same server.
	// 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

	// PublicSuffixList supplies a public-suffix database to the cookie jar
	// (see net/http/cookiejar.PublicSuffixList). Without one, the jar accepts
	// cookies on public suffixes and applies looser domain matching, which can
	// leak cookies across unrelated subdomains. Recommended value:
	// golang.org/x/net/publicsuffix.List. Default: nil (no PSL enforcement).
	PublicSuffixList cookiejar.PublicSuffixList

	// EnableDoH enables DNS-over-HTTPS for DNS resolution.
	// Default: false.
	EnableDoH bool

	// DoHCacheTTL is the cache duration for DoH DNS responses.
	// Default: 5 minutes. The TTL is applied to every record uniformly and
	// overrides the authoritative record TTL from the DNS answer (a record
	// with a 30s server TTL is cached for the full DoHCacheTTL, and a record
	// with a 24h TTL is re-queried after DoHCacheTTL).
	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 1MB, net/http.DefaultMaxHeaderBytes).
	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
result, err := client.Get(url, httpc.WithSecureCookie(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.

When a method receives an absolute URL pointing at a host other than the base host, session headers and cookies are neither sent nor captured, so base-domain credentials cannot leak to third-party origins.

Session capture is STATIC: before each request the session reads cookies and headers from the built-in WithCookies/WithCookieMap/WithCookieString and WithHeader/WithHeaderMap options without executing them, so per-request options run exactly once. Cookies or headers set by a custom (unrecognized) RequestOption are therefore not persisted into the session — register shared session state via SetCookie/SetHeader/SessionManager rather than an inline option. *FormData must still not be shared across concurrent requests (see WithFile).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 — only when the final response landed on the base origin (result.RequestURL after redirects, see targetsFinalURL). Like Request, session capture is static (see the DomainClient type doc): request options run exactly once.

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL).

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 http/https URL, it is used directly; other schemes are not treated as absolute (see buildURL). The context parameter allows for timeout and cancellation control. This method makes DomainClient compatible with the Client interface.

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 returns the base URL this client was constructed with.
	URL() string
	// Domain returns the hostname of the base URL (without port). Origin
	// scoping (host:port comparison) is enforced internally by
	// targetsBaseHost — compare against url.URL.Host, not Domain(), when
	// matching origins.
	Domain() string

	// SetHeader sets a session header applied to every subsequent request.
	SetHeader(key, value string) error
	// SetHeaders adds or updates multiple session headers (matching keys
	// are replaced; other session headers persist).
	SetHeaders(headers map[string]string) error
	// DeleteHeader removes one session header.
	DeleteHeader(key string)
	// ClearHeaders removes all session headers.
	ClearHeaders()
	// GetHeaders returns a copy of the current session headers.
	GetHeaders() map[string]string

	// SetCookie adds a cookie to the domain session.
	SetCookie(cookie *http.Cookie) error
	// SetCookies adds multiple cookies to the domain session.
	SetCookies(cookies []*http.Cookie) error
	// DeleteCookie removes one session cookie by name.
	DeleteCookie(name string)
	// ClearCookies removes all session cookies.
	ClearCookies()
	// GetCookies returns the session cookies.
	GetCookies() []*http.Cookie
	// GetCookie returns one session cookie by name, or nil.
	GetCookie(name string) *http.Cookie

	// Session returns the underlying SessionManager for direct inspection.
	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 via its SessionManager, which is the single cookie store — the engine-level cookie jar is deliberately not enabled. Pass DefaultConfig() for defaults, or use NewDomainDefault(baseURL) as a zero-argument shortcut.

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
	// fails the download: fresh downloads remove their temp file (any
	// pre-existing destination is untouched), resumed downloads are
	// truncated back to the offset the session started at — preserving the
	// previously downloaded prefix for the next resume attempt.
	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.

Size limit: downloads are subject to the client's Security.MaxResponseBodySize (default 10 MB). A body exceeding the limit fails with a "streamed response body exceeds size limit" error — it is never silently truncated. Raise the limit on Config.Security for large-file workloads.

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

type DownloadProgressCallback func(downloaded, total int64, speed float64)

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 number of bytes written by this download. A resumed
	// download counts only the bytes it appended; the file's total size is
	// the resumed prefix plus BytesWritten (the final ProgressCallback
	// invocation reports that total).
	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. The download is subject to the client's Security.MaxResponseBodySize (default 10 MB); oversize bodies fail with an error — see DownloadConfig.

type ErrorType added in v1.3.8

type ErrorType = engine.ErrorType

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

type FileData = types.FileData

FileData represents a file to be uploaded in a multipart form. Alias for types.FileData to avoid importing the internal package.

type FormData

type FormData = types.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

type Handler = types.Handler

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) live on Config.Defaults (RequestDefaults); the redirect policy lives on Config.Security (FollowRedirects, MaxRedirects).

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 using SourceIPKey and UserIDKey from the context passed to Client.Request, falling back to the request's own context when set via WithContext.

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

type ProxyStrategy = proxypool.Strategy

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
}

RequestDefaults configures per-request defaults applied to every outgoing request: the User-Agent header and default headers. The redirect policy is NOT part of this struct — it lives on Config.Security (FollowRedirects, MaxRedirects).

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
	// ProxyURL is the URL of the proxy that served the final attempt of this
	// request, as selected by the configured proxy (a single Connection.ProxyURL
	// or a proxy pool entry). Empty when no proxy was used or the connection
	// was direct. With proxy rotation each retry attempt may use a different
	// proxy; this field reports the proxy that produced the returned response
	// (see Attempts for the number of attempts made).
	ProxyURL string
	// 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 interface {
	// contains filtered or unexported methods
}

RequestOption is a value that modifies a request before it is sent. It is a named interface (rather than the former func alias) so that DomainClient's session capture can type-switch over the built-in option types and extract cookies/headers without executing the option. The unexported apply method means only this package (and RequestOptionFunc) can implement it; custom behavior is expressed as a function adapted by RequestOptionFunc.

client.Get(url, httpc.RequestOptionFunc(func(req httpc.RequestMutator) error {
    req.SetHeader("X-Custom", "value")
    return nil
}))

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 ErrInvalidCredentials 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 ErrInvalidCredentials 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 empty (nil or zero length — matching WithBody(BodyBinary)) or the content type contains invalid characters.

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: when Security.MaxRequestBodySize is configured, io.Reader bodies are enforced at send time by a counting reader that aborts the transfer once the limit is crossed (known body types are sized before sending).

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 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 WithCookies 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 one or more cookies to the request after validation. 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:

// Single cookie
result, err := client.Get("https://api.example.com",
    httpc.WithCookies([]http.Cookie{{Name: "session_id", Value: "abc123"}}),
)

// Multiple cookies
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. Multiple WithFile options merge their files into a single multipart body; the same field name is overwritten. Any non-form body set earlier is replaced. The merge mutates the request's existing *FormData in place — see the WithFormData doc for why a FormData value must not be shared across concurrent requests. 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).

Concurrency: the *FormData is used as-is, not copied. A single FormData value must not be shared across concurrently executing requests — the WithFile option mutates its Files map in place, and concurrent requests sharing one value would race on that map.

Validation: field names, filenames, and per-file ContentType values containing control characters (CR/LF/NUL/DEL, etc.) are rejected — they would otherwise allow MIME header injection in the outgoing body. The same check runs at the encoding layer, so a FormData constructed directly (not via WithFile) is subject to identical limits. A nil *FileData map entry fails the request rather than silently dropping the file. 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 ErrInvalidMaxRedirects 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.

Counting matches net/http: the limit includes the initial request, so WithMaxRedirects(n) follows at most n-1 redirects (the default 10 follows 9).

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.

Note: retrying follows the client's idempotency policy — non-idempotent methods (POST, PATCH, custom) are not retried unless the client sets Retry.RetryNonIdempotent or this request passes WithRetryNonIdempotent(true); without either of those, MaxRetries only bounds idempotent requests.

func WithNoTimeout added in v1.6.3

func WithNoTimeout() RequestOption

WithNoTimeout disables the client-level request timeout (Config.Timeouts.Request) for this single request, allowing it to run as long as the server takes. It does not affect dial/TLS/response-header timeouts, and two limits still apply: an explicit WithTimeout on the same request, and any deadline on the caller-provided context (via WithContext or the ctx parameter) are always honored.

Use for long-running calls (large uploads/downloads, slow reports) on a client whose default timeout would otherwise cut them off.

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 WithRetryNonIdempotent added in v1.6.3

func WithRetryNonIdempotent(allow bool) RequestOption

WithRetryNonIdempotent overrides, for this single request, whether non-idempotent methods (POST, PATCH, custom methods) may be retried. It takes precedence over the client-level Retry.RetryNonIdempotent setting in both directions: WithRetryNonIdempotent(true) retries a POST on a client that otherwise forbids it, and WithRetryNonIdempotent(false) pins a single attempt on a client that allows it.

SAFETY: enabling retries for a non-idempotent request means a timeout or retryable 5xx may cause the request body to be sent more than once. Only use it against endpoints that tolerate replay (or protect them with an idempotency key). See RetryConfig.RetryNonIdempotent for the default policy.

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 WithCookies/WithCookieMap options:

// Correct order: add cookies first, then validate
result, err := client.Get(url,
    httpc.WithCookies(sessionCookies),
    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 request fails with ErrStreamBodyRequiresDownload: those methods buffer the body into a Result and cannot hand the stream to the caller, so an empty body would be returned silently. To 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 zero, negative, or exceeds 30 minutes. Zero is rejected because the engine reads it as "not set" — the request would silently fall back to the client's default timeout; use WithNoTimeout to disable the timeout for a request.

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 RequestOptionFunc added in v1.7.0

type RequestOptionFunc func(RequestMutator) error

RequestOptionFunc adapts a function literal to the RequestOption interface, mirroring net/http's Handler/HandlerFunc split. Use it to write a custom per-request option without naming the internal request type.

client.Get(url, httpc.RequestOptionFunc(func(req httpc.RequestMutator) error {
    req.SetHeader("X-Custom", "value")
    return nil
}))

A nil RequestOptionFunc is a no-op when applied.

type RequestReader added in v1.7.0

type RequestReader = types.RequestReader

RequestReader provides read-only access to request data. Alias for types.RequestReader to avoid importing the internal package.

type RequestWriter added in v1.7.0

type RequestWriter = types.RequestWriter

RequestWriter provides write-only access to request data. Alias for types.RequestWriter to avoid importing the internal package.

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 ResponseReader added in v1.7.0

type ResponseReader = types.ResponseReader

ResponseReader provides read-only access to response data for middleware. Alias for types.ResponseReader to avoid importing the internal package.

type ResponseWriter added in v1.7.0

type ResponseWriter = types.ResponseWriter

ResponseWriter provides write-only access to response data. Alias for types.ResponseWriter to avoid importing the internal package.

type Result added in v1.3.0

type Result struct {
	// Request describes the request as finally sent (after redirects,
	// retries, and middleware).
	Request *RequestInfo
	// Response carries the final response data; nil when the request errored
	// before a response arrived.
	Response *ResponseInfo
	// Meta carries request metadata (duration, attempts, proxy used); nil
	// only for zero-value Results constructed by callers.
	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(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

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

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

func (r *Result) Body() string

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

func (r *Result) GetCookie(name string) *http.Cookie

GetCookie returns a response cookie by name, or nil if not found.

func (*Result) GetRequestCookie added in v1.3.0

func (r *Result) GetRequestCookie(name string) *http.Cookie

GetRequestCookie returns a request cookie by name, or nil if not found.

func (*Result) HasCookie added in v1.3.0

func (r *Result) HasCookie(name string) bool

HasCookie returns true if a response cookie with the given name exists.

func (*Result) HasRequestCookie added in v1.3.0

func (r *Result) HasRequestCookie(name string) bool

HasRequestCookie returns true if a request cookie with the given name exists.

func (*Result) IsClientError added in v1.3.0

func (r *Result) IsClientError() bool

IsClientError returns true if the response status code indicates a client error (4xx).

func (*Result) IsRedirect added in v1.3.0

func (r *Result) IsRedirect() bool

IsRedirect returns true if the response status code indicates a redirect (3xx).

func (*Result) IsServerError added in v1.3.0

func (r *Result) IsServerError() bool

IsServerError returns true if the response status code indicates a server error (5xx).

func (*Result) IsSuccess added in v1.3.0

func (r *Result) IsSuccess() bool

IsSuccess returns true if the response status code indicates success (2xx).

func (*Result) Proto added in v1.3.8

func (r *Result) Proto() string

Proto returns the HTTP protocol version (e.g., "HTTP/1.1", "HTTP/2.0").

func (*Result) RawBody added in v1.3.0

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

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

func (r *Result) RequestCookies() []*http.Cookie

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

func (r *Result) ResponseCookies() []*http.Cookie

ResponseCookies returns the cookies from the response. Returns nil if the Result or Response is nil.

func (*Result) SaveToFile added in v1.3.0

func (r *Result) SaveToFile(filePath string) error

SaveToFile saves the response body to a file at the specified path, overwriting any existing destination unconditionally (unlike Download, which returns ErrFileExists unless Overwrite is set). Returns ErrResponseBodyEmpty if the response body is nil or empty, or ErrDownloadInProgress when a Download (or another SaveToFile) targeting the same path is already running in this process. The file path is validated for security (path traversal, symlinks, etc.).

The body is written to a "<path>.httpc-tmp" sibling and atomically renamed into place, matching writeDownloadBody's TOCTOU posture: a symlink swapped in between prepareFilePath's Lstat check and the write is never opened for writing, and an interrupted save never leaves a partial destination file.

func (*Result) StatusCode added in v1.3.0

func (r *Result) StatusCode() int

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

func (r *Result) String() string

String returns a human-readable representation of the Result. Sensitive headers are masked. Body content is never included — only its size — because response bodies frequently carry credentials (OAuth token endpoints, session payloads) that must not reach logs.

func (*Result) Unmarshal added in v1.3.8

func (r *Result) Unmarshal(v any) error

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 — except when ProxyRotateOnStatus or ProxyRotatePerRequest is
	// configured with a ProxyPool larger than 1: the budget is then raised to
	// len(ProxyPool)-1 so every proxy is tried at least once, even from an
	// explicit 0 (see calculateMaxRetries in config_convert.go).
	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. A value of 0 selects the 30s default — the cap cannot be
	// disabled through this field (the config conversion replaces 0 with the
	// default before the engine sees it).
	MaxRetryDelay time.Duration

	// RetryNonIdempotent allows retrying non-idempotent methods (POST, PATCH,
	// and custom methods). Default: false — such requests execute exactly
	// once, because a timeout or retryable 5xx may arrive after the server
	// already committed the operation, and replaying the body would duplicate
	// it (duplicate payment, double insert, ...). Enable only when the
	// endpoint is known to tolerate replay, or guard it with an idempotency
	// key. Idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS, TRACE) are
	// always retried subject to MaxRetries.
	RetryNonIdempotent bool

	// CustomPolicy overrides the built-in retry logic. Default: nil.
	// Like the built-in policy, it is only consulted for idempotent
	// methods; a custom policy does not re-enable retries for POST/PATCH
	// unless RetryNonIdempotent (or WithRetryNonIdempotent) is also set.
	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

	// TLSFingerprint enables browser transport fingerprinting: TLS
	// ClientHello (JA3/JA4), HTTP/2 frames (SETTINGS order and values,
	// connection window, initial stream id, pseudo-header order), and a
	// browser-coherent ordered header block with the browser's exact wire
	// casing and a version-matched User-Agent.
	//
	// The transport is github.com/bogdanfinn/tls-client; httpc supplies the
	// ClientHello spec, the HTTP/2 SETTINGS and the header tables itself, so
	// profile data lives in this library and can target a browser build ahead
	// of any upstream release.
	//
	// Values are preset names for the two shipped browser profiles —
	// "chrome" (Chrome 155) and "firefox" (Firefox 158) — optionally with an
	// OS suffix: "chrome-windows", "chrome-macos", "chrome-linux",
	// "chrome-android", "chrome-ios" (and the firefox-* equivalents), plus
	// the aliases "chrome-latest", "chrome-155", "chrome-152" and
	// "firefox-148" (retired majors, pinned), "firefox-latest",
	// "firefox-158", "android-chrome-latest", "ios-chrome-latest". Empty
	// string (default) uses the standard Go stack with no spoofing. The iOS
	// presets speak WebKit (as every iOS browser must): Safari's TLS and
	// HTTP/2 shapes with CriOS/FxiOS User-Agents, and "safari-ios" is Safari
	// itself on that same data. There is no desktop-Safari profile.
	//
	// Behavior notes when set:
	//   - The httpc engine (redirects, retries, middleware, streaming) stays
	//     in control; only the transport layer is replaced.
	//   - Proxy pools, rotation, and circuit breaking keep working; HTTP,
	//     HTTPS and SOCKS5 (socks5/socks5h) proxies are supported on the
	//     fingerprint path — socks4/socks4a are rejected at validation
	//     (x/net/proxy implements SOCKS5 only). The proxy is fixed per
	//     connection pool: rotation selects a different
	//     pool and never re-points a live one.
	//   - The preset's header set is authoritative: same-named request
	//     headers (User-Agent, Accept, Accept-Language, ...) are replaced by
	//     the browser profile's values so the wire stays coherent with the
	//     spoofed ClientHello. Custom headers pass through untouched — in
	//     particular, an explicitly set User-Agent does NOT override the
	//     preset on this path.
	//   - Header names are written with the browser's own casing (lower-case
	//     sec-ch-ua, Title-Case everything else), including on HTTP/1.1.
	//   - Redirect hops stay browser-coherent: sec-fetch-site is recomputed
	//     against the previous hop's URL, sec-fetch-user is dropped after
	//     the first hop, and a 301/302/303-downgraded fetch request keeps
	//     fetch-style headers after turning into GET.
	//   - Protocol selection follows the transport's ALPN negotiation, so a
	//     server that only speaks HTTP/1.1 simply gets HTTP/1.1 — no manual
	//     fallback, and no request is ever replayed behind the engine's back.
	//     HTTP/3 is never attempted: a QUIC connection uses a separate TLS
	//     stack that bypasses CertificatePinner, and losing the pin silently
	//     is worse than not racing protocols.
	//   - Certificate pinning works on this path: CertificatePinner runs on
	//     every fingerprinted handshake (under InsecureSkipVerify it becomes
	//     the only gate, pinning the leaf certificate — the same trust model
	//     as the standard path).
	//   - Connection.EnableHTTP2=false pins the fingerprint path to HTTP/1.1
	//     and rewrites the ClientHello's ALPN list to match, mirroring the
	//     standard stack's protocol choice.
	//   - The fingerprint path uses its own connection-pool sizing
	//     (MaxIdleConns 512 / MaxConnsPerHost 128): Connection.MaxIdleConns
	//     and Connection.MaxConnsPerHost apply to the standard transport only.
	//   - TLSConfig is mutually exclusive with this field (validation
	//     rejects the combination). MinTLSVersion/MaxTLSVersion are silently
	//     ignored when TLSFingerprint is set — the preset's ClientHello
	//     dictates the version range.
	//   - SSRF protection uses a resolve-then-validate pre-flight instead of
	//     the standard path's dial-layer validation; redirects are re-checked
	//     per hop by the engine. The pre-flight is weaker than the standard
	//     path in two ways: a TOCTOU window remains between validation and
	//     the backend's own DNS resolution, and a host resolving to a MIX of
	//     public and private addresses passes ("at least one allowed IP") —
	//     the backend's second resolution may then land on the private
	//     record, deterministically and without DNS rebinding. The standard
	//     path dials only validated IP literals and has neither gap.
	//   - Response bodies are decoded by httpc itself (gzip/deflate/br/zstd)
	//     and handed to the engine as identity bodies.
	//   - Fingerprinted connections are not counted in pool metrics and do
	//     not use Connection.EnableDoH (the backend resolves DNS itself).
	TLSFingerprint string

	// TLSFingerprintDisableSessionTickets turns off TLS session ticket
	// caching and resumption on the fingerprint path. By default (false) the
	// Chrome profiles cache session tickets per connection pool (like real
	// browsers, a repeat connection to a host resumes with a PSK instead of a
	// full handshake); profiles whose ClientHello carries no pre_shared_key
	// extension (Firefox, the iOS WebKit profiles) always full-handshake
	// regardless. Set true to force a full handshake on every connection —
	// for fingerprint-rotation pipelines that want each connection fully
	// independent, or to rule resumption out while debugging a target.
	TLSFingerprintDisableSessionTickets 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.
	// It applies only to compressed responses (the size after inflation);
	// non-compressed bodies are always limited by MaxResponseBodySize.
	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

	// 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).
	//
	// Combines with TLSFingerprint: on the fingerprint path the pinner runs
	// as the spoofed handshake's VerifyPeerCertificate hook; when
	// InsecureSkipVerify is also set, the pinner is the only verification
	// gate and pins the leaf certificate (verified chains are unavailable
	// when verification is skipped).
	//
	// 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

	// SensitiveHeaders extends the set of header names treated as credentials
	// when a redirect carries the request to a different origin: the built-in
	// set (Authorization, Proxy-Authorization, Cookie, X-Api-Key,
	// X-Auth-Token) is always stripped on cross-origin hops — net/http itself
	// only covers the first three, and a custom credential header such as
	// "X-Secret-Key" would otherwise be forwarded verbatim to whatever the
	// Location header points at (open-redirect credential leak, CWE-525).
	// Entries are canonicalized (matching is case-insensitive) and deduped;
	// the built-in set is always stripped regardless. Default: nil.
	//
	// Note: masking in Result.String() and audit output covers only the
	// built-in sensitive names; headers listed here remain visible there.
	SensitiveHeaders []string

	// FollowRedirects controls automatic redirect following. Default: true.
	FollowRedirects bool

	// MaxRedirects limits automatic redirects. Default: 10.
	// 0 is the unset sentinel — it falls back to the default of 10, matching
	// WithMaxRedirects; to disable redirects entirely set FollowRedirects=false.
	MaxRedirects int
}

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 = httpc.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. Create one with NewSessionManager or NewSessionManagerDefault; a zero-value SessionManager is also usable — its internal maps initialize lazily on the first write.

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. The lookup is case-insensitive: a header stored as "Cache-Control" is removed by DeleteHeader("cache-control") and vice versa.

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. Cookies whose Expires moment has passed are omitted (see isExpiredCookie) — the returned view matches what a request would actually send.

func (*SessionManager) GetHeaders added in v1.3.8

func (s *SessionManager) GetHeaders() map[string]string

GetHeaders returns a copy of all session headers. Keys are in canonical (http.CanonicalHeaderKey) form — see SetHeader.

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. A cookie with RFC 6265 deletion semantics (MaxAge < 0 or an Expires in the past) removes the stored cookie instead of being stored — same rule the capture path applies (see isDeletionCookie).

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. The key is stored in canonical (http.CanonicalHeaderKey) form, so "cache-control" and "Cache-Control" address the same entry and the last write wins. 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. Keys are stored in canonical form (see SetHeader); input keys are visited in sorted order so a header supplied under multiple casings resolves to the later key in sort order, not Go's random map iteration order. 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.

Directories

Path Synopsis
internal
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.
fingerprint
Package fingerprint implements browser transport fingerprinting (TLS ClientHello + HTTP/2 frames + ordered, case-exact header block) as a standard net/http RoundTripper, so the httpc engine (redirects, retries, middleware, streaming) stays authoritative.
Package fingerprint implements browser transport fingerprinting (TLS ClientHello + HTTP/2 frames + ordered, case-exact header block) as a standard net/http RoundTripper, so the httpc engine (redirects, retries, middleware, streaming) stays authoritative.
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.

Jump to

Keyboard shortcuts

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