httpc

package module
v1.3.8 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 23 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 - Production-Ready HTTP Client for Go

Go Version Go Reference License Security Zero Deps

A high-performance HTTP client library for Go with enterprise-grade security, zero external dependencies, and production-ready defaults.

中文文档


✨ 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
🛠️ Developer Friendly Clean API, intuitive options pattern, comprehensive documentation
📦 Zero Dependencies Pure Go standard library, no external packages
✅ Production Ready Battle-tested defaults, extensive test coverage
🍪 Cookie Management Full cookie jar support with security validation
📁 File Operations Secure file download with progress tracking and resume support

📦 Installation

go get -u github.com/cybergodev/httpc

🚀 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())
}

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

🔧 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)
httpc.WithFormData(formData)
httpc.WithFile("file", "document.pdf", fileBytes)

// Raw body
httpc.WithBody([]byte("raw data"))
httpc.WithBinary(binaryData, "application/pdf")
Cookies
// Single cookie
httpc.WithCookie(http.Cookie{Name: "session", Value: "abc123"})

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

// Cookie string
httpc.WithCookieString("session=abc123; token=xyz")
Request Control
// Context for cancellation
httpc.WithContext(ctx)

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

// Retry configuration
httpc.WithMaxRetries(3)

// Redirect control
httpc.WithFollowRedirects(false)
httpc.WithMaxRedirects(5)
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(form), WithFile(field, filename, content), WithBody([]byte), WithBinary([]byte, contentType?)
Cookies WithCookie(cookie), WithCookieMap(map), WithCookieString("a=1; b=2"), WithSecureCookie(config)
Control WithTimeout(dur), WithMaxRetries(n), WithContext(ctx)
Redirects WithFollowRedirects(bool), WithMaxRedirects(n)
Callbacks WithOnRequest(fn), WithOnResponse(fn)

📥 Response Handling

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

// Quick access
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{}
result.Unmarshal(&data)

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

// Request cookies sent
reqCookie := result.GetRequestCookie("token")

// Save response to file
result.SaveToFile("response.json")

// Metadata
fmt.Println(result.Meta.Duration)      // Request duration
fmt.Println(result.Meta.Attempts)      // Retry count
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())

⏱️ 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.DownloadFile(
    "https://example.com/file.zip",
    "downloads/file.zip",
)
fmt.Printf("Downloaded: %s at %s/s\n",
    httpc.FormatBytes(result.BytesWritten),
    httpc.FormatSpeed(result.AverageSpeed))
Download with Progress
opts := httpc.DefaultDownloadOptions("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.DownloadWithOptions(url, opts)
Resume Download
opts := httpc.DefaultDownloadOptions("downloads/large.zip")
opts.ResumeDownload = true
result, _ := httpc.DownloadWithOptions(url, opts)
if result.Resumed {
    fmt.Println("Download resumed from previous position")
}

🌐 Domain Client (Session Management)

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

client, _ := httpc.NewDomain("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")

// Cookie management
client.SetCookie(&http.Cookie{Name: "session", Value: "abc"})
client.GetCookie("session")
client.DeleteCookie("session")
client.ClearCookies()

// Header management
client.SetHeaders(map[string]string{"X-App": "v1"})
client.GetHeaders()
client.DeleteHeader("X-Old")
client.ClearHeaders()

⚙️ Configuration

Preset Configurations
// Production-ready defaults (recommended)
client, _ := httpc.New(httpc.DefaultConfig())

// 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
    Timeout:               30 * time.Second,
    DialTimeout:           10 * time.Second,
    TLSHandshakeTimeout:   10 * time.Second,
    ResponseHeaderTimeout: 30 * time.Second,
    IdleConnTimeout:       90 * time.Second,

    // Connection
    MaxIdleConns:      100,
    MaxConnsPerHost:   20,
    EnableHTTP2:       true,
    EnableCookies:     false,

    // Security
    MinTLSVersion:       tls.VersionTLS12,
    MaxTLSVersion:       tls.VersionTLS13,
    MaxResponseBodySize: 50 * 1024 * 1024, // 50 MB
    AllowPrivateIPs:     true,

    // Retry
    MaxRetries:    3,
    RetryDelay:    1 * time.Second,
    BackoffFactor: 2.0,
    EnableJitter:  true,

    // Other
    UserAgent:       "MyApp/1.0",
    FollowRedirects: true,
    MaxRedirects:    10,
}
client, _ := httpc.New(config)
Configuration Options
Option Type Default Description
Timeouts
Timeout time.Duration 30s Overall request timeout
DialTimeout time.Duration 10s TCP connection timeout
TLSHandshakeTimeout time.Duration 10s TLS handshake timeout
ResponseHeaderTimeout time.Duration 30s Response header timeout
IdleConnTimeout time.Duration 90s Idle connection timeout
Connection
MaxIdleConns int 50 Max idle connections
MaxConnsPerHost int 10 Max connections per host
ProxyURL string "" Proxy URL (http/socks5)
EnableSystemProxy bool false Auto-detect system proxy
EnableHTTP2 bool true Enable HTTP/2
EnableCookies bool false Enable cookie jar
EnableDoH bool false Enable DNS-over-HTTPS
DoHCacheTTL time.Duration 5m DoH cache duration
Security
TLSConfig *tls.Config nil Custom TLS config
MinTLSVersion uint16 TLS 1.2 Minimum TLS version
MaxTLSVersion uint16 TLS 1.3 Maximum TLS version
InsecureSkipVerify bool false Skip TLS verification (testing only!)
MaxResponseBodySize int64 10MB Max response body size
AllowPrivateIPs bool true Allow private IPs (SSRF)
ValidateURL bool true Enable URL validation
ValidateHeaders bool true Enable header validation
StrictContentLength bool true Strict content-length check
RedirectWhitelist []string nil Allowed redirect domains
Retry
MaxRetries int 3 Max retry attempts
RetryDelay time.Duration 1s Initial retry delay
BackoffFactor float64 2.0 Backoff multiplier
EnableJitter bool true Add jitter to retries
CustomRetryPolicy RetryPolicy nil Custom retry logic
Other
Middlewares []MiddlewareFunc nil Middleware chain
UserAgent string "httpc/1.0" Default User-Agent
Headers map[string]string {} Default headers
FollowRedirects bool true Follow redirects
MaxRedirects int 10 Max redirect count

🔌 Middleware

Built-in Middleware
// Request logging
httpc.LoggingMiddleware(log.Printf)

// Panic recovery
httpc.RecoveryMiddleware()

// Request ID
httpc.RequestIDMiddleware("X-Request-ID", nil)

// Timeout enforcement
httpc.TimeoutMiddleware(30*time.Second)

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

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

// Security audit
httpc.AuditMiddleware(func(a httpc.AuditEvent) {
    log.Printf("[AUDIT] %s %s -> %d (%v)", a.Method, a.URL, a.StatusCode, a.Duration)
})
Chain Multiple Middleware
chainedMiddleware := httpc.Chain(
    httpc.RecoveryMiddleware(),
    httpc.LoggingMiddleware(log.Printf),
    httpc.RequestIDMiddleware("X-Request-ID", nil),
    httpc.HeaderMiddleware(map[string]string{"X-App": "v1"}),
)
config.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.Config{
    ProxyURL: "http://127.0.0.1:8080",
    // Or SOCKS5: "socks5://127.0.0.1:1080"
}

// System proxy auto-detection (Windows/macOS/Linux)
config := &httpc.Config{
    EnableSystemProxy: true,  // Reads from environment and system settings
}

🔒 Security Features

Feature Description
TLS 1.2+ Modern encryption standards by default
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.Config{
    RedirectWhitelist: []string{"api.example.com", "secure.example.com"},
}
SSRF Protection

By default, AllowPrivateIPs is true for compatibility. Enable SSRF protection when making requests to user-provided URLs:

// Enable SSRF protection
cfg := httpc.DefaultConfig()
cfg.AllowPrivateIPs = false
client, _ := httpc.New(cfg)

// Or use the secure preset
client, _ := httpc.New(httpc.SecureConfig())

⚠️ 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())
}
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 // All retries exhausted
    ErrorTypeTLS            // TLS handshake error
    ErrorTypeCertificate    // Certificate validation error
    ErrorTypeDNS            // DNS resolution error
    ErrorTypeValidation     // Request validation error
    ErrorTypeHTTP           // HTTP-level error (4xx, 5xx)
)

🔄 Concurrency Safety

HTTPC is designed to be goroutine-safe:

client, _ := httpc.New()
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()
Performance Optimization
// Release Result back to pool after use (reduces GC pressure)
result, _ := httpc.Get(url)
defer httpc.ReleaseResult(result)

Thread Safety Guarantees:

  • All Client methods are safe for concurrent use
  • Package-level functions safely use a shared default client
  • Response objects can be safely read from multiple goroutines
  • Internal metrics use atomic operations

📚 Documentation

Resource Description
Getting Started Installation and first steps
Configuration Client configuration and presets
Request Options Complete options reference
Error Handling Error handling patterns
File Download File download with progress
HTTP Redirects Redirect handling and tracking
Cookie API Cookie management
Security Security features and best practices
Example Code
Directory Description
01_quickstart Basic usage
02_core_features Headers, auth, body formats
03_advanced File upload, download, retry, middleware

📄 License

MIT License - see LICENSE file for details.


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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClientClosed is returned when attempting to use a closed client.
	// This occurs after calling Close() on a client instance.
	ErrClientClosed = errors.New("client is closed")

	// ErrNilConfig is returned when a nil configuration is provided.
	// Always provide a valid Config or use DefaultConfig().
	ErrNilConfig = errors.New("config cannot be nil")

	// ErrInvalidURL is returned when URL validation fails.
	// URLs must have a valid scheme (http/https) and host.
	ErrInvalidURL = errors.New("invalid URL")

	// 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")

	// 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 DownloadOptions.
	ErrFileExists = errors.New("file already exists")

	// ErrResponseBodyEmpty is returned when attempting to parse empty response body.
	// Check response.RawBody before calling JSON() 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")
)
View Source
var ClassifyError = engine.ClassifyError

ClassifyError classifies an error into a ClientError with context. This is useful for custom error handling and logging.

Example:

var clientErr *httpc.ClientError
if errors.As(err, &clientErr) {
    if clientErr.IsRetryable() {
        // Retry the request
    }
}

Functions

func ClearAllPools added in v1.3.8

func ClearAllPools()

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

This function clears:

  • Result pool (client level)
  • URL cache (request processor)
  • Request pools (strings/bytes readers, string builders)
  • Response pools (gzip/flate readers, buffers)
  • Transport pools (redirect settings, cookie maps)

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

func FormatSpeed

func FormatSpeed(bytesPerSecond float64) string

func NewCookieJar

func NewCookieJar() (http.CookieJar, error)

NewCookieJar creates a new cookie jar for cookie management.

func ReleaseResult added in v1.3.8

func ReleaseResult(r *Result)

ReleaseResult returns a Result to the pool for reuse. Call this when you're done with the Result to reduce garbage collection pressure. WARNING: Do not use the Result after calling ReleaseResult.

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. Only *clientImpl instances created by this package are supported.

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.

Types

type AuditContextKey added in v1.3.8

type AuditContextKey string

AuditContextKey is the type for context keys used in audit middleware.

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

type AuditEvent added in v1.3.8

type AuditEvent struct {
	Timestamp     time.Time     `json:"timestamp"`
	Method        string        `json:"method"`
	URL           string        `json:"url"` // Sanitized (credentials removed)
	StatusCode    int           `json:"statusCode"`
	Duration      time.Duration `json:"duration"`
	Attempts      int           `json:"attempts"`
	Error         error         `json:"error,omitempty"`
	SourceIP      string        `json:"sourceIP,omitempty"`
	UserID        string        `json:"userID,omitempty"`
	RedirectChain []string      `json:"redirectChain,omitempty"`
}

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 AuditMiddlewareConfig added in v1.3.8

type AuditMiddlewareConfig struct {
	// Format specifies the output format: "text" (default) or "json"
	Format string

	// IncludeHeaders includes request/response headers in the audit log
	IncludeHeaders bool

	// MaskHeaders is a list of header names to mask (e.g., "Authorization", "Cookie")
	MaskHeaders []string

	// SanitizeError removes sensitive information from error messages
	SanitizeError bool
}

AuditMiddlewareConfig configures the audit middleware behavior.

func DefaultAuditMiddlewareConfig added in v1.3.8

func DefaultAuditMiddlewareConfig() *AuditMiddlewareConfig

DefaultAuditMiddlewareConfig returns the default audit middleware configuration.

type CacheStats added in v1.3.8

type CacheStats struct {
	URLCacheSize int // Number of entries in the URL cache
}

CacheStats holds statistics about internal caches.

func GetCacheStats added in v1.3.8

func GetCacheStats() CacheStats

GetCacheStats returns statistics about internal caches and pools. Useful for monitoring memory usage in production environments.

type Client

type Client interface {
	Doer

	// Convenience methods for common HTTP verbs
	Get(url string, options ...RequestOption) (*Result, error)
	Post(url string, options ...RequestOption) (*Result, error)
	Put(url string, options ...RequestOption) (*Result, error)
	Patch(url string, options ...RequestOption) (*Result, error)
	Delete(url string, options ...RequestOption) (*Result, error)
	Head(url string, options ...RequestOption) (*Result, error)
	Options(url string, options ...RequestOption) (*Result, error)

	// File download methods
	DownloadFile(url string, filePath string, options ...RequestOption) (*DownloadResult, error)
	DownloadWithOptions(url string, downloadOpts *DownloadOptions, 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(config ...*Config) (Client, error)

New creates a new HTTP client with the given configuration. If no configuration is provided or nil is passed, DefaultConfig() is used.

Examples:

// Use default configuration
client, err := httpc.New()

// Use default configuration (explicit nil)
client, err := httpc.New(nil)

// Use custom configuration
cfg := httpc.DefaultConfig()
cfg.Timeout = 60 * time.Second
client, err := httpc.New(cfg)

// Use preset configuration
client, err := httpc.New(httpc.SecureConfig())

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 {

	// Timeout is the overall request timeout including retries.
	// Default: 30s. Set to 0 for no timeout (not recommended for production).
	Timeout time.Duration

	// DialTimeout is the maximum time to wait for a TCP connection.
	// Default: 10s. This is the timeout for the initial connection.
	DialTimeout time.Duration

	// TLSHandshakeTimeout is the maximum time to wait for TLS handshake.
	// Default: 10s. Only applies to HTTPS connections.
	TLSHandshakeTimeout time.Duration

	// ResponseHeaderTimeout is the maximum time to wait for response headers.
	// Default: 30s. The connection is dropped if headers are not received in time.
	ResponseHeaderTimeout time.Duration

	// IdleConnTimeout is the maximum time an idle connection remains open.
	// Default: 90s. Connections are closed after this period of inactivity.
	IdleConnTimeout time.Duration

	// MaxIdleConns is the maximum number of idle connections across all hosts.
	// Default: 50. Higher values improve performance for multi-host scenarios.
	MaxIdleConns int

	// MaxConnsPerHost is the maximum connections per host (idle + active).
	// Default: 10. Adjust based on server capacity and expected load.
	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.
	// Reads from Windows registry, macOS system settings, and environment variables.
	// Ignored if ProxyURL is set. Default: false.
	EnableSystemProxy bool

	// EnableHTTP2 enables HTTP/2 protocol support.
	// Default: true. Disable for HTTP/1.1-only environments.
	EnableHTTP2 bool

	// EnableCookies enables automatic cookie handling with a cookie jar.
	// Default: false. Enable for session-based authentication.
	EnableCookies bool

	// EnableDoH enables DNS-over-HTTPS for DNS resolution.
	// Provides privacy and bypasses DNS-based filtering. Default: false.
	EnableDoH bool

	// DoHCacheTTL is the cache duration for DoH DNS responses.
	// Default: 5 minutes. Ignored if EnableDoH is false.
	DoHCacheTTL time.Duration

	// TLSConfig provides custom TLS configuration. If set, MinTLSVersion and
	// MaxTLSVersion are ignored. Default: nil (uses secure defaults).
	TLSConfig *tls.Config

	// MinTLSVersion is the minimum TLS version. Default: TLS 1.2 (0x0303).
	// Use tls.VersionTLS12 or tls.VersionTLS13.
	MinTLSVersion uint16

	// MaxTLSVersion is the maximum TLS version. Default: TLS 1.3 (0x0304).
	MaxTLSVersion uint16

	// InsecureSkipVerify disables TLS certificate verification.
	// WARNING: This should only be used in testing. Default: false.
	InsecureSkipVerify bool

	// MaxResponseBodySize limits the maximum response body size in bytes.
	// Default: 10MB. Set to 0 for no limit (not recommended).
	MaxResponseBodySize int64

	// AllowPrivateIPs permits connections to private IP addresses (SSRF protection).
	// Default: true for compatibility. Set to false to enable SSRF protection
	// and block connections to private/reserved IP addresses.
	AllowPrivateIPs bool

	// ValidateURL enables URL validation before sending requests.
	// Default: true. Disable only for compatibility with unusual URL schemes.
	ValidateURL bool

	// ValidateHeaders enables header validation before sending requests.
	// Default: true. Disable only for compatibility with non-standard headers.
	ValidateHeaders bool

	// StrictContentLength enables strict Content-Length validation.
	// Default: true. Disable only for compatibility with broken servers.
	StrictContentLength bool

	// CookieSecurity enables cookie security attribute validation.
	// When set, cookies are validated against the security requirements.
	// Use validation.DefaultCookieSecurityConfig() or validation.StrictCookieSecurityConfig().
	// Default: nil (no cookie security validation).
	CookieSecurity *validation.CookieSecurityConfig

	// RedirectWhitelist specifies allowed domains for redirects.
	// When set, redirects are only allowed to domains in this list.
	// This provides an additional layer of SSRF protection.
	// Default: nil (no whitelist, all redirects allowed if SSRF check passes).
	RedirectWhitelist []string

	// MaxRetries is the maximum number of retry attempts for transient failures.
	// Default: 3. Set to 0 to disable retries.
	MaxRetries int

	// RetryDelay is the initial delay between retry attempts.
	// Default: 1s. Actual delay increases with BackoffFactor.
	RetryDelay time.Duration

	// BackoffFactor multiplies RetryDelay after each failed attempt.
	// Default: 2.0. Must be between 1.0 and 10.0.
	BackoffFactor float64

	// EnableJitter enables jitter in retry delay calculations.
	// Default: true. Helps prevent thundering herd problems.
	EnableJitter bool

	// CustomRetryPolicy allows providing a custom retry policy implementation.
	// If set, it overrides MaxRetries, RetryDelay, BackoffFactor, and EnableJitter.
	CustomRetryPolicy RetryPolicy

	// Middlewares contains middleware functions for request/response interception.
	// Middlewares are executed in order for requests and reverse order for responses.
	// Default: nil (no middlewares).
	Middlewares []MiddlewareFunc

	// UserAgent sets the User-Agent header for all requests.
	// Default: "httpc/1.0". Max length: 512 characters.
	UserAgent string

	// Headers contains default headers added to every request.
	// Can be overridden per-request using WithHeader option.
	Headers map[string]string

	// FollowRedirects controls automatic redirect following.
	// Default: true. Set to false to handle redirects manually.
	FollowRedirects bool

	// MaxRedirects limits the number of automatic redirects.
	// Default: 10. Set to 0 for unlimited (not recommended).
	MaxRedirects int
}

Config defines the HTTP client configuration with a flat structure. All configuration options are directly accessible at the top level. All duration values use time.Duration (e.g., 30 * time.Second).

Use DefaultConfig() for production-ready defaults, or use preset configurations like SecureConfig(), PerformanceConfig(), or MinimalConfig().

Example:

cfg := httpc.DefaultConfig()
cfg.Timeout = 60 * time.Second
cfg.MaxRetries = 5
cfg.ProxyURL = "http://proxy:8080"
cfg.AllowPrivateIPs = true
client, err := httpc.New(cfg)

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with production-ready defaults. The returned config is safe for modification.

SSRF Protection Note: By default, AllowPrivateIPs is true for maximum compatibility with VPNs, proxies, and corporate networks. If you need SSRF (Server-Side Request Forgery) protection, set AllowPrivateIPs = false or use SecureConfig() preset:

// For SSRF protection:
cfg := httpc.DefaultConfig()
cfg.AllowPrivateIPs = false
// OR use the secure preset:
cfg := httpc.SecureConfig()

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, and relaxed validation.

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)

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 {
	// 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.

func NewDomain added in v1.3.0

func NewDomain(baseURL string, config ...*Config) (*DomainClient, error)

NewDomain creates a new DomainClient scoped to the specified base URL. The client automatically manages cookies and headers across requests. If no configuration is provided or nil is passed, DefaultConfig() is used. Note: Cookies are automatically enabled for DomainClient.

Examples:

// Use default configuration
dc, err := httpc.NewDomain("https://api.example.com")

// Use custom configuration
cfg := httpc.DefaultConfig()
cfg.Timeout = 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 (*DomainClient) ClearCookies added in v1.3.0

func (dc *DomainClient) ClearCookies()

ClearCookies removes all cookies from the session.

func (*DomainClient) ClearHeaders added in v1.3.0

func (dc *DomainClient) ClearHeaders()

ClearHeaders removes all headers from the session.

func (*DomainClient) Close added in v1.3.0

func (dc *DomainClient) Close() error

Close closes the underlying HTTP client and releases resources.

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.

func (*DomainClient) DeleteCookie added in v1.3.0

func (dc *DomainClient) DeleteCookie(name string)

DeleteCookie removes a cookie from the session by name.

func (*DomainClient) DeleteHeader added in v1.3.0

func (dc *DomainClient) DeleteHeader(key string)

DeleteHeader removes a header from the session.

func (*DomainClient) Domain added in v1.3.8

func (dc *DomainClient) Domain() string

Domain returns the domain name (host without port)

func (*DomainClient) DownloadFile added in v1.3.5

func (dc *DomainClient) DownloadFile(path string, filePath string, options ...RequestOption) (*DownloadResult, error)

DownloadFile downloads a file from the specified path to the given file path.

func (*DomainClient) DownloadWithOptions added in v1.3.5

func (dc *DomainClient) DownloadWithOptions(path string, downloadOpts *DownloadOptions, options ...RequestOption) (*DownloadResult, error)

DownloadWithOptions downloads a file with custom download options.

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.

func (*DomainClient) GetCookie added in v1.3.0

func (dc *DomainClient) GetCookie(name string) *http.Cookie

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

func (*DomainClient) GetCookies added in v1.3.0

func (dc *DomainClient) GetCookies() []*http.Cookie

GetCookies returns a copy of all session cookies.

func (*DomainClient) GetHeaders added in v1.3.0

func (dc *DomainClient) GetHeaders() map[string]string

GetHeaders returns a copy of all session headers.

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.

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.

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.

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.

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.

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

func (*DomainClient) SetCookie added in v1.3.0

func (dc *DomainClient) SetCookie(cookie *http.Cookie) error

SetCookie adds or updates a cookie in the session.

func (*DomainClient) SetCookies added in v1.3.0

func (dc *DomainClient) SetCookies(cookies []*http.Cookie) error

SetCookies adds or updates multiple cookies in the session.

func (*DomainClient) SetHeader added in v1.3.0

func (dc *DomainClient) SetHeader(key, value string) error

SetHeader adds or updates a header in the session.

func (*DomainClient) SetHeaders added in v1.3.0

func (dc *DomainClient) SetHeaders(headers map[string]string) error

SetHeaders adds or updates multiple headers in the session.

func (*DomainClient) URL added in v1.3.8

func (dc *DomainClient) URL() string

URL returns the base URL

type DomainClienter added in v1.3.8

type DomainClienter interface {
	Client

	// URL accessors
	URL() string
	Domain() string

	// Session header management
	SetHeader(key, value string) error
	SetHeaders(headers map[string]string) error
	DeleteHeader(key string)
	ClearHeaders()
	GetHeaders() map[string]string

	// Session cookie management
	SetCookie(cookie *http.Cookie) error
	SetCookies(cookies []*http.Cookie) error
	DeleteCookie(name string)
	ClearCookies()
	GetCookies() []*http.Cookie
	GetCookie(name string) *http.Cookie

	// Session access
	Session() *SessionManager
}

DomainClienter extends Client with domain-scoped operations. It provides session management for cookies and headers across requests to a specific domain.

type DownloadOptions

type DownloadOptions struct {
	FilePath         string
	ProgressCallback DownloadProgressCallback
	Overwrite        bool
	ResumeDownload   bool
}

DownloadOptions configures file download behavior.

func DefaultDownloadOptions

func DefaultDownloadOptions(filePath string) *DownloadOptions

DefaultDownloadOptions creates download options with default settings. Overwrite and ResumeDownload are both false by default.

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      string
	BytesWritten  int64
	Duration      time.Duration
	AverageSpeed  float64
	StatusCode    int
	ContentLength int64
	Resumed       bool
}

DownloadResult contains information about a completed download.

func DownloadFile

func DownloadFile(url string, filePath string, options ...RequestOption) (*DownloadResult, error)

DownloadFile downloads a file from the given URL to the specified file path using the default client. Returns DownloadResult with download statistics or an error if the download fails.

func DownloadWithOptions

func DownloadWithOptions(url string, downloadOpts *DownloadOptions, options ...RequestOption) (*DownloadResult, error)

DownloadWithOptions downloads a file with custom download options using the default client. Returns DownloadResult with download statistics or an error if the download fails.

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. This is a type alias to types.FileData for backward compatibility.

type FormData

type FormData = types.FormData

FormData represents multipart form data for HTTP requests. This is a type alias to types.FormData for backward compatibility.

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. This is the core function signature for request processing in the middleware chain.

This is a type alias to the shared types package, ensuring compile-time type compatibility between public and internal layers.

type MiddlewareFunc added in v1.3.8

type MiddlewareFunc = types.MiddlewareFunc

MiddlewareFunc wraps a Handler with additional functionality. Middleware can inspect/modify requests, handle responses, add logging, etc.

This is a type alias to the shared types package, ensuring compile-time type compatibility between public and internal layers.

func AuditMiddleware added in v1.3.8

func AuditMiddleware(onAudit func(event AuditEvent)) MiddlewareFunc

AuditMiddleware creates a middleware that generates security audit events. This is designed for high-security scenarios (financial, medical, government) where comprehensive request logging is required for compliance.

The onAudit callback receives an AuditEvent with sanitized URL (credentials removed), request metadata, and response information. SourceIP and UserID are extracted from the request context using SourceIPKey and UserIDKey.

Example:

auditMiddleware := httpc.AuditMiddleware(func(event httpc.AuditEvent) {
    log.Printf("[AUDIT] %s %s -> %d (%v) user=%s ip=%s",
        event.Method, event.URL, event.StatusCode, event.Duration,
        event.UserID, event.SourceIP)
})

func AuditMiddlewareJSON added in v1.3.8

func AuditMiddlewareJSON(onAudit func(event AuditEvent)) MiddlewareFunc

AuditMiddlewareJSON creates a middleware that outputs audit events as JSON. This is a convenience function for structured logging systems. like ELK, Splunk, or cloud logging services.

Example:

auditMiddleware := httpc.AuditMiddlewareJSON(func(event httpc.AuditEvent) {
    data, _ := json.Marshal(event)
    log.Printf("[AUDIT] %s", data)
})

func AuditMiddlewareWithConfig added in v1.3.8

func AuditMiddlewareWithConfig(onAudit func(event AuditEvent), config *AuditMiddlewareConfig) MiddlewareFunc

AuditMiddlewareWithConfig creates a middleware that generates security audit events with configurable output format and options.

Example:

config := &httpc.AuditMiddlewareConfig{
    Format: "json",
    IncludeHeaders: true,
}
auditMiddleware := httpc.AuditMiddlewareWithConfig(func(event httpc.AuditEvent) {
    // event will be formatted according to config.Format
    log.Printf("[AUDIT] %v", event)
}, config)

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(headers map[string]string) MiddlewareFunc

HeaderMiddleware creates a middleware that adds static headers to every request. Existing headers with the same keys will be overwritten. Headers are validated for security (CRLF injection prevention) before being set.

func LoggingMiddleware added in v1.3.8

func LoggingMiddleware(log func(format string, args ...any)) MiddlewareFunc

LoggingMiddleware creates a middleware that logs request and response information. The log function receives formatted log messages (similar to log.Printf).

func MetricsMiddleware added in v1.3.8

func MetricsMiddleware(onMetrics func(method, url string, statusCode int, duration time.Duration, err error)) MiddlewareFunc

MetricsMiddleware creates a middleware that collects request metrics. The onMetrics callback is invoked with metrics after each request completes.

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(headerName string, generator func() string) MiddlewareFunc

RequestIDMiddleware creates a middleware that adds a unique request ID to each request. The request ID is added to the request headers with the specified header name. If generator is nil, a default time-based ID generator is used.

func TimeoutMiddleware added in v1.3.8

func TimeoutMiddleware(timeout time.Duration) MiddlewareFunc

TimeoutMiddleware creates a middleware that enforces a maximum duration for requests. 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.

type RequestInfo added in v1.3.0

type RequestInfo struct {
	URL     string
	Method  string
	Headers http.Header
	Cookies []*http.Cookie
}

type RequestMeta added in v1.3.0

type RequestMeta struct {
	Duration      time.Duration
	Attempts      int
	RedirectChain []string
	RedirectCount int
}

type RequestMutator added in v1.3.8

type RequestMutator = types.RequestMutator

RequestMutator provides read-write access to request data for middleware. Middleware can inspect and modify request properties before the request is sent.

This is a type alias to the shared types package, ensuring compile-time type compatibility between public and internal layers.

type RequestOption

type RequestOption = engine.RequestOption

RequestOption is a function that modifies a request. This is a type alias to the engine's RequestOption for unified type handling.

func WithBasicAuth

func WithBasicAuth(username, password string) RequestOption

func WithBearerToken

func WithBearerToken(token string) RequestOption

func WithBinary

func WithBinary(data []byte, contentType ...string) RequestOption

func WithBody

func WithBody(body any) RequestOption

func WithContext

func WithContext(ctx context.Context) RequestOption

func WithCookie

func WithCookie(cookie http.Cookie) RequestOption

func WithCookieMap added in v1.3.8

func WithCookieMap(cookies map[string]string) RequestOption

WithCookieMap sets multiple cookies from a map of name-value pairs. This is a convenience method for setting multiple simple cookies at once. For cookies with additional attributes (Domain, Path, Secure, etc.), use WithCookie or WithCookieString instead.

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

func WithFile

func WithFile(fieldName, filename string, content []byte) RequestOption

func WithFollowRedirects added in v1.3.0

func WithFollowRedirects(follow bool) RequestOption

func WithForm

func WithForm(data map[string]string) RequestOption

func WithFormData

func WithFormData(data *FormData) RequestOption

func WithHeader

func WithHeader(key, value string) RequestOption

func WithHeaderMap

func WithHeaderMap(headers map[string]string) RequestOption

WithHeaderMap sets multiple headers from a map.

func WithJSON

func WithJSON(data any) RequestOption

func WithMaxRedirects added in v1.3.0

func WithMaxRedirects(maxRedirects int) RequestOption

func WithMaxRetries

func WithMaxRetries(maxRetries int) RequestOption

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
    }),
)

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
    }),
)

func WithQuery

func WithQuery(key string, value any) RequestOption

func WithQueryMap

func WithQueryMap(params map[string]any) RequestOption

WithQueryMap sets multiple query parameters from a map.

func WithSecureCookie added in v1.3.8

func WithSecureCookie(securityConfig *validation.CookieSecurityConfig) RequestOption

WithSecureCookie creates a request option that enforces cookie security attributes. on the cookie being added to the request. The securityConfig defines the required security attributes (Secure, HttpOnly, SameSite).

Example:

security := &validation.CookieSecurityConfig{
	RequireSecure:     true,
	RequireHttpOnly:   true,
	RequireSameSite:   "Strict",
	AllowSameSiteNone: false,
}
result, err := client.Get("https://api.example.com",
	httpc.WithSecureCookie(security),
)

func WithTimeout

func WithTimeout(timeout time.Duration) RequestOption

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

type ResponseInfo added in v1.3.0

type ResponseInfo struct {
	StatusCode    int
	Status        string
	Proto         string
	Headers       http.Header
	Body          string
	RawBody       []byte
	ContentLength int64
	Cookies       []*http.Cookie
}

type ResponseMutator added in v1.3.8

type ResponseMutator = types.ResponseMutator

ResponseMutator provides read-write access to response data. Middleware can inspect and modify response properties after the request completes. This is useful for:

  • Response caching middleware
  • Response transformation (e.g., JSON pretty-printing)
  • Content encoding/decoding
  • Response filtering

This is a type alias to the shared types package, ensuring compile-time type compatibility between public and internal layers.

type Result added in v1.3.0

type Result struct {
	Request  *RequestInfo
	Response *ResponseInfo
	Meta     *RequestMeta
}

func Delete

func Delete(url string, options ...RequestOption) (*Result, error)

func Get

func Get(url string, options ...RequestOption) (*Result, error)
func Head(url string, options ...RequestOption) (*Result, error)

func Options

func Options(url string, options ...RequestOption) (*Result, error)

func Patch

func Patch(url string, options ...RequestOption) (*Result, error)

func Post

func Post(url string, options ...RequestOption) (*Result, error)

func Put

func Put(url string, options ...RequestOption) (*Result, error)

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

func (*Result) GetCookie added in v1.3.0

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

func (*Result) GetRequestCookie added in v1.3.0

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

func (*Result) HasCookie added in v1.3.0

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

func (*Result) HasRequestCookie added in v1.3.0

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

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

func (*Result) RequestCookies added in v1.3.0

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

func (*Result) ResponseCookies added in v1.3.0

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

func (*Result) SaveToFile added in v1.3.0

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

func (*Result) StatusCode added in v1.3.0

func (r *Result) StatusCode() int

func (*Result) String added in v1.3.0

func (r *Result) String() string

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 RetryPolicy added in v1.3.8

type RetryPolicy = types.RetryPolicy

RetryPolicy defines the interface for custom retry behavior. This is a type alias to types.RetryPolicy for convenience.

type SessionManager added in v1.3.8

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

SessionManager manages session state including cookies and headers for DomainClient instances. It provides thread-safe access to session data.

func NewSessionManager added in v1.3.8

func NewSessionManager() *SessionManager

NewSessionManager creates a new SessionManager with empty session state.

func NewSessionManagerWithSecurity added in v1.3.8

func NewSessionManagerWithSecurity(cookieSecurity *validation.CookieSecurityConfig) *SessionManager

NewSessionManagerWithSecurity creates a new SessionManager with cookie security validation. The cookieSecurity config is used to validate cookies when they are set.

func (*SessionManager) CaptureFromOptions added in v1.3.8

func (s *SessionManager) CaptureFromOptions(options []RequestOption)

CaptureFromOptions extracts cookies and headers from RequestOptions and stores them in the session.

func (*SessionManager) ClearCookies added in v1.3.8

func (s *SessionManager) ClearCookies()

ClearCookies removes all cookies from the session.

func (*SessionManager) ClearHeaders added in v1.3.8

func (s *SessionManager) ClearHeaders()

ClearHeaders removes all headers from the session.

func (*SessionManager) DeleteCookie added in v1.3.8

func (s *SessionManager) DeleteCookie(name string)

DeleteCookie removes a cookie from the session by name.

func (*SessionManager) DeleteHeader added in v1.3.8

func (s *SessionManager) DeleteHeader(key string)

DeleteHeader removes a header from the session.

func (*SessionManager) GetCookie added in v1.3.8

func (s *SessionManager) GetCookie(name string) *http.Cookie

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

func (*SessionManager) GetCookies added in v1.3.8

func (s *SessionManager) GetCookies() []*http.Cookie

GetCookies returns a copy of all session cookies. Optimized to reduce allocations by pre-allocating slice with exact capacity.

func (*SessionManager) GetHeaders added in v1.3.8

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

GetHeaders returns a copy of all session headers.

func (*SessionManager) PrepareOptions added in v1.3.8

func (s *SessionManager) PrepareOptions() []RequestOption

PrepareOptions creates RequestOptions from the current session state. This is used to apply session cookies and headers to outgoing requests.

func (*SessionManager) SetCookie added in v1.3.8

func (s *SessionManager) SetCookie(cookie *http.Cookie) error

SetCookie adds or updates a cookie in the session. Returns an error if the cookie is nil or invalid. If cookie security is configured, validates against security requirements.

func (*SessionManager) SetCookieSecurity added in v1.3.8

func (s *SessionManager) SetCookieSecurity(config *validation.CookieSecurityConfig)

SetCookieSecurity sets the cookie security configuration. This affects all subsequent SetCookie calls.

func (*SessionManager) SetCookies added in v1.3.8

func (s *SessionManager) SetCookies(cookies []*http.Cookie) error

SetCookies adds or updates multiple cookies in the session. Returns an error if any cookie is nil or invalid. If cookie security is configured, validates against security requirements.

func (*SessionManager) SetHeader added in v1.3.8

func (s *SessionManager) SetHeader(key, value string) error

SetHeader adds or updates a header in the session. Returns an error if the header key or value is invalid.

func (*SessionManager) SetHeaders added in v1.3.8

func (s *SessionManager) SetHeaders(headers map[string]string) error

SetHeaders adds or updates multiple headers in the session. Returns an error if any header key or value is invalid.

func (*SessionManager) UpdateFromResult added in v1.3.8

func (s *SessionManager) UpdateFromResult(result *Result)

UpdateFromResult updates session cookies from a Result.

Directories

Path Synopsis
internal
dns
types
Package types provides shared type definitions used across the httpc library.
Package types provides shared type definitions used across the httpc library.

Jump to

Keyboard shortcuts

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