httpc

package module
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 18 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 License Security Performance Thread Safe

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

📖 中文文档 | 📚 Full Documentation


Why HTTPC?

  • 🛡️ Secure by Default - TLS 1.2+, SSRF protection, CRLF injection prevention
  • ⚡ High Performance - Connection pooling, HTTP/2, goroutine-safe operations
  • 📊 Built-in Resilience - Smart retry with exponential backoff and jitter
  • 🎯 Developer Friendly - Clean API, functional options, comprehensive error handling
  • 🔧 Zero Dependencies - Pure Go stdlib, no external packages
  • 🚀 Production Ready - Battle-tested defaults, extensive test coverage

Quick Start

go get -u github.com/cybergodev/httpc
package main

import (
    "fmt"
    "log"
    "github.com/cybergodev/httpc"
)

func main() {
    // Simple GET request
    resp, err := httpc.Get("https://api.example.com/users")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Status: %d\n", resp.StatusCode())

    // POST with JSON and authentication
    user := map[string]string{"name": "John", "email": "john@example.com"}
    resp, err = httpc.Post("https://api.example.com/users",
        httpc.WithJSON(user),
        httpc.WithBearerToken("your-token"),
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Created: %s\n", resp.Body())
}

📖 See more examples | 🚀 Getting Started Guide

Core Features

HTTP Methods

All standard HTTP methods with clean, intuitive API:

// GET - Retrieve data
resp, err := httpc.Get("https://api.example.com/users",
    httpc.WithQuery("page", 1),
    httpc.WithBearerToken("token"),
)

// POST - Create resource
resp, err := httpc.Post("https://api.example.com/users",
    httpc.WithJSON(user),
    httpc.WithBearerToken("token"),
)

// PUT - Full update
resp, err := httpc.Put("https://api.example.com/users/123",
    httpc.WithJSON(updatedUser),
)

// PATCH - Partial update
resp, err := httpc.Patch("https://api.example.com/users/123",
    httpc.WithJSON(map[string]string{"email": "new@example.com"}),
)

// DELETE - Remove resource
resp, err := httpc.Delete("https://api.example.com/users/123")

// HEAD, OPTIONS, and custom methods also supported

Request Options

Customize requests using functional options (all options start with With):

// Headers & Authentication
httpc.WithHeader("X-API-Key", "key")
httpc.WithBearerToken("token")
httpc.WithBasicAuth("user", "pass")

// Query Parameters
httpc.WithQuery("page", 1)
httpc.WithQueryMap(map[string]interface{}{"page": 1, "limit": 20})

// Request Body
httpc.WithJSON(data)              // JSON body
httpc.WithForm(formData)          // Form data
httpc.WithFile("file", "doc.pdf", content)  // File upload

// Cookies
httpc.WithCookieString("session=abc123; token=xyz789")  // Parse cookie string
httpc.WithCookieValue("name", "value")                  // Single cookie
httpc.WithCookie(cookie)                                // http.Cookie object
httpc.WithCookies(cookies)                              // Multiple cookies

// Redirects
httpc.WithFollowRedirects(false)  // Disable automatic redirect following
httpc.WithMaxRedirects(5)         // Limit maximum redirects (0-50)

// Timeout & Retry
httpc.WithTimeout(30*time.Second)
httpc.WithMaxRetries(3)
httpc.WithContext(ctx)

// Combine multiple options
resp, err := httpc.Post(url,
    httpc.WithJSON(data),
    httpc.WithBearerToken("token"),
    httpc.WithTimeout(30*time.Second),
    httpc.WithMaxRetries(2),
)

📖 Complete Options Reference

Response Data Access

HTTPC returns a Result object that provides structured access to request and response information:

result, err := httpc.Get("https://api.example.com/users/123")
if err != nil {
    log.Fatal(err)
}

// Quick access methods
statusCode := result.StatusCode()    // HTTP status code
body := result.Body()                // Response body as string
rawBody := result.RawBody()          // Response body as []byte

// Detailed response information
response := result.Response
fmt.Printf("Status: %d %s\n", response.StatusCode, response.Status)
fmt.Printf("Content-Length: %d\n", response.ContentLength)
fmt.Printf("Headers: %v\n", response.Headers)
fmt.Printf("Cookies: %v\n", response.Cookies)

// Request information
request := result.Request
fmt.Printf("Method: %s\n", request.Method)
fmt.Printf("URL: %s\n", request.URL)
fmt.Printf("Request Headers: %v\n", request.Headers)

// Metadata
meta := result.Meta
fmt.Printf("Duration: %v\n", meta.Duration)
fmt.Printf("Attempts: %d\n", meta.Attempts)
fmt.Printf("Redirects: %d\n", meta.RedirectCount)

Response Handling

result, err := httpc.Get(url)
if err != nil {
    log.Fatal(err)
}

// Status checking
if result.IsSuccess() {        // 2xx
    fmt.Println("Success!")
}

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

// Access response data
fmt.Printf("Status: %d\n", result.StatusCode())
fmt.Printf("Body: %s\n", result.Body())
fmt.Printf("Duration: %v\n", result.Meta.Duration)
fmt.Printf("Attempts: %d\n", result.Meta.Attempts)

// Work with cookies
cookie := result.GetCookie("session_id")

// Access detailed response information
fmt.Printf("Content-Length: %d\n", result.Response.ContentLength)
fmt.Printf("Response Headers: %v\n", result.Response.Headers)
fmt.Printf("Request Headers: %v\n", result.Request.Headers)

Automatic Response Decompression

HTTPC automatically detects and decompresses compressed HTTP responses:

// Request compressed response
result, err := httpc.Get("https://api.example.com/data",
    httpc.WithHeader("Accept-Encoding", "gzip, deflate"),
)

// Response is automatically decompressed
fmt.Printf("Decompressed body: %s\n", result.Body())
fmt.Printf("Original encoding: %s\n", result.Response.Headers.Get("Content-Encoding"))

Supported Encodings:

  • ✅ gzip - Fully supported (compress/gzip)
  • ✅ deflate - Fully supported (compress/flate)

Note: Decompression is automatic when the server sends a Content-Encoding header. The library handles this transparently, so you always receive decompressed content.

File Download

// Simple download
result, err := httpc.DownloadFile(
    "https://example.com/file.zip",
    "downloads/file.zip",
)
fmt.Printf("Downloaded: %s at %s\n", 
    httpc.FormatBytes(result.BytesWritten),
    httpc.FormatSpeed(result.AverageSpeed))

// Download with progress tracking
opts := httpc.DefaultDownloadOptions("downloads/large-file.zip")
opts.ProgressCallback = func(downloaded, total int64, speed float64) {
    percentage := float64(downloaded) / float64(total) * 100
    fmt.Printf("\rProgress: %.1f%% - %s", percentage, httpc.FormatSpeed(speed))
}
result, err := httpc.DownloadWithOptions(url, opts)

// Resume interrupted downloads
opts.ResumeDownload = true
result, err := httpc.DownloadWithOptions(url, opts)

// Download with authentication
result, err := httpc.DownloadFile(url, "file.zip",
    httpc.WithBearerToken("token"),
    httpc.WithTimeout(5*time.Minute),
)

📖 File Download Guide

Configuration

Quick Start with Presets

// Default - Balanced for production (recommended)
client, err := httpc.New()

// Secure - Maximum security (strict validation, minimal retries)
client, err := httpc.NewSecure()

// Performance - Optimized for high throughput
client, err := httpc.NewPerformance()

// Minimal - Lightweight for simple requests
client, err := httpc.NewMinimal()

// Testing - Permissive for development (NEVER use in production)
client, err := httpc.New(httpc.TestingConfig())

Custom Configuration

config := &httpc.Config{
    Timeout:             30 * time.Second,
    MaxRetries:          3,
    MaxIdleConns:        100,
    MaxConnsPerHost:     20,
    MinTLSVersion:       tls.VersionTLS12,
    MaxResponseBodySize: 50 * 1024 * 1024, // 50 MB
    UserAgent:           "MyApp/1.0",
    EnableHTTP2:         true,
}
client, err := httpc.New(config)

📖 Configuration Guide

Error Handling

result, err := httpc.Get(url)
if err != nil {
    // Check for specific error types
    var httpErr *httpc.HTTPError
    if errors.As(err, &httpErr) {
        fmt.Printf("HTTP %d: %s\n", httpErr.StatusCode, httpErr.Status)
    }
    
    // Check for timeout
    if strings.Contains(err.Error(), "timeout") {
        return fmt.Errorf("request timed out")
    }
    
    return err
}

// Check response status
if !result.IsSuccess() {
    return fmt.Errorf("unexpected status: %d", result.StatusCode())
}

// Access detailed error information
if result.IsClientError() {
    fmt.Printf("Client error (4xx): %d\n", result.StatusCode())
} else if result.IsServerError() {
    fmt.Printf("Server error (5xx): %d\n", result.StatusCode())
}

📖 Error Handling Guide

Advanced Features

Client Lifecycle Management

// Create reusable client
client, err := httpc.New()
if err != nil {
    log.Fatal(err)
}
defer client.Close()  // Always close to release resources

// Or use package-level functions (auto-managed)
defer httpc.CloseDefaultClient()
result, err := httpc.Get(url)

Automatic Retries

// Configure at client level
config := httpc.DefaultConfig()
config.MaxRetries = 3
config.BackoffFactor = 2.0
client, err := httpc.New(config)

// Or per-request
result, err := httpc.Get(url, httpc.WithMaxRetries(5))

Context Support

// Timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
result, err := client.Get(url, httpc.WithContext(ctx))

// Cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
    time.Sleep(5 * time.Second)
    cancel()
}()
result, err := client.Get(url, httpc.WithContext(ctx))

HTTP Redirects

// Automatic redirect following (default)
result, err := httpc.Get("https://example.com/redirect")
fmt.Printf("Followed %d redirects\n", result.Meta.RedirectCount)

// Disable redirects for specific request
result, err := httpc.Get(url, httpc.WithFollowRedirects(false))
if result.IsRedirect() {
    fmt.Printf("Redirect to: %s\n", result.Response.Headers.Get("Location"))
}

// Limit redirects
result, err := httpc.Get(url, httpc.WithMaxRedirects(5))

// Track redirect chain
for i, url := range result.Meta.RedirectChain {
    fmt.Printf("%d. %s\n", i+1, url)
}

📖 Redirect Guide

// Automatic cookie handling
config := httpc.DefaultConfig()
config.EnableCookies = true
client, err := httpc.New(config)

// Login sets cookies
client.Post("https://example.com/login", httpc.WithForm(credentials))

// Subsequent requests include cookies automatically
client.Get("https://example.com/profile")

// Manual cookie setting
// Parse cookie string (from browser dev tools or server response)
result, err := httpc.Get("https://api.example.com/data",
    httpc.WithCookieString("PSID=4418ECBB1281B550; PSTM=1733760779; BS=kUwNTVFcEUBUItoc"),
)

// Set individual cookies
result, err = httpc.Get("https://api.example.com/data",
    httpc.WithCookieValue("session", "abc123"),
    httpc.WithCookieValue("token", "xyz789"),
)

// Use http.Cookie objects for advanced settings
cookie := &http.Cookie{
    Name:     "secure_session",
    Value:    "encrypted_value",
    Secure:   true,
    HttpOnly: true,
    SameSite: http.SameSiteStrictMode,
}
result, err = httpc.Get("https://api.example.com/data", httpc.WithCookie(cookie))

📖 Cookie API Reference

Domain Client - Automatic State Management

For applications that make multiple requests to the same domain, DomainClient provides automatic Cookie and Header management:

// Create domain-specific client
client, err := httpc.NewDomain("https://api.example.com")
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// First request - server sets cookies
resp1, err := client.Get("/login",
    httpc.WithJSON(credentials),
)

// Cookies from resp1 are automatically saved and sent in subsequent requests
resp2, err := client.Get("/profile")  // Cookies automatically included

// Set persistent headers (sent with all requests)
client.SetHeader("Authorization", "Bearer "+token)
client.SetHeader("X-API-Key", "your-api-key")

// All subsequent requests include these headers
resp3, err := client.Get("/data")  // Headers + Cookies automatically included

// Override per-request (doesn't affect persistent state)
resp4, err := client.Get("/special",
    httpc.WithHeader("Accept", "application/xml"),  // Override for this request only
)

// Manual cookie management
client.SetCookie(&http.Cookie{Name: "session", Value: "abc123"})
client.SetCookies([]*http.Cookie{
    {Name: "pref", Value: "dark"},
    {Name: "lang", Value: "en"},
})

// Query state
cookies := client.GetCookies()
headers := client.GetHeaders()
sessionCookie := client.GetCookie("session")

// Clear state
client.DeleteCookie("session")
client.DeleteHeader("X-API-Key")
client.ClearCookies()
client.ClearHeaders()

Real-World Example - Login Flow:

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

// Step 1: Login (server sets session cookie)
loginResp, _ := client.Post("/auth/login",
    httpc.WithJSON(map[string]string{
        "username": "user@example.com",
        "password": "secret",
    }),
)

// Step 2: Extract token and set as persistent header
var loginData map[string]string
loginResp.JSON(&loginData)
client.SetHeader("Authorization", "Bearer "+loginData["token"])

// Step 3: Make API calls (cookies + auth header automatically sent)
profileResp, _ := client.Get("/api/user/profile")
dataResp, _ := client.Get("/api/user/data")
settingsResp, _ := client.Put("/api/user/settings",
    httpc.WithJSON(newSettings),
)

// All requests automatically include:
// - Session cookies from login response
// - Authorization header
// - Any other persistent headers/cookies

Key Features:

  • Automatic Cookie Persistence - Cookies from responses are saved and sent in subsequent requests
  • Automatic Header Persistence - Set headers once, used in all requests
  • Per-Request Overrides - Use WithCookies() and WithHeaderMap() to override for specific requests
  • Thread-Safe - All operations are goroutine-safe
  • Manual Control - Full API for inspecting and modifying state

📖 See full example

Security & Performance

Security Features

  • TLS 1.2+ by default - Modern encryption standards
  • SSRF Protection - Pre-DNS and post-DNS validation blocks private IPs
  • CRLF Injection Prevention - Header and URL validation
  • Input Validation - Comprehensive validation of all user inputs
  • Path Traversal Protection - Safe file operations
  • Configurable Limits - Response size, timeout, connection limits

Performance Optimizations

  • Connection Pooling - Efficient connection reuse with per-host limits
  • HTTP/2 Support - Multiplexing for better performance
  • Goroutine-Safe - All operations thread-safe with atomic operations
  • Smart Retry - Exponential backoff with jitter reduces server load
  • Memory Efficient - Configurable limits prevent memory exhaustion

Concurrency Safety

HTTPC is designed for concurrent use from the ground up:

// ✅ Safe: Share a single client across goroutines
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()

Thread Safety Guarantees:

  • ✅ All Client methods are safe for concurrent use
  • ✅ Package-level functions (Get, Post, etc.) use a shared default client safely
  • ✅ Response objects can be read from multiple goroutines after return
  • ✅ Internal metrics and connection pools use atomic operations
  • ✅ Config is deep-copied on client creation to prevent modification issues

Best Practices:

  • Create one client and reuse it across your application
  • Don't modify Config after passing it to New()
  • Response objects are safe to read but shouldn't be modified concurrently

Testing: Run make test-race to verify race-free operation in your code.

Performance Benchmarks

HTTPC is designed for high performance with minimal allocations:

# Run benchmarks
go test -bench=. -benchmem ./...

# Example results (your results may vary):
BenchmarkClient_Get-8           5000    250000 ns/op    1024 B/op    8 allocs/op
BenchmarkClient_Post-8          4000    300000 ns/op    1536 B/op   12 allocs/op
BenchmarkClient_Concurrent-8   10000    150000 ns/op     512 B/op    4 allocs/op

Performance Features:

  • Zero-copy operations where possible
  • Connection pooling with configurable limits
  • Hot path optimization with minimal allocations
  • Atomic operations for thread-safe counters
  • Efficient string operations with pre-allocated buffers

📖 Security Guide

Documentation

Guides

Examples

Contributing

Contributions welcome! Please open an issue first for major changes.

License

MIT License - see LICENSE file for details.


Made with ❤️ by the CyberGoDev team

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

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 bytes in human-readable format (e.g., "1.50 KB", "2.00 MB").

func FormatSpeed

func FormatSpeed(bytesPerSecond float64) string

FormatSpeed formats speed in human-readable format (e.g., "1.50 KB/s", "2.00 MB/s").

func NewCookieJar

func NewCookieJar() (http.CookieJar, error)

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. Returns an error if the client is nil or not created with httpc.New().

func ValidateConfig added in v1.1.0

func ValidateConfig(cfg *Config) error

ValidateConfig validates the configuration with reasonable limits. ValidateConfig validates the configuration with comprehensive security checks. All limits are enforced to prevent resource exhaustion and security issues.

Types

type Client

type Client interface {
	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)

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

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

	Close() error
}

Client represents the HTTP client interface. All methods are safe for concurrent use by multiple goroutines.

func New

func New(config ...*Config) (Client, error)

func NewMinimal added in v1.1.0

func NewMinimal() (Client, error)

NewMinimal creates a new client with minimal features and lightweight configuration. This preset is ideal for simple, one-off requests where you don't need retries or advanced features.

func NewPerformance added in v1.1.0

func NewPerformance() (Client, error)

NewPerformance creates a new client optimized for high-throughput scenarios. This preset uses aggressive connection pooling, longer timeouts, and faster retry intervals for maximum performance.

func NewSecure added in v1.1.0

func NewSecure() (Client, error)

NewSecure creates a new client with security-focused configuration. This preset prioritizes security over performance with strict validation, minimal retries, and conservative connection limits.

type Config

type Config struct {
	Timeout         time.Duration
	MaxIdleConns    int
	MaxConnsPerHost int
	ProxyURL        string

	TLSConfig           *tls.Config
	MinTLSVersion       uint16
	MaxTLSVersion       uint16
	InsecureSkipVerify  bool
	MaxResponseBodySize int64
	AllowPrivateIPs     bool // Allow requests to private/reserved IP ranges (default: true for usability)
	StrictContentLength bool

	MaxRetries    int
	RetryDelay    time.Duration
	BackoffFactor float64

	UserAgent       string
	Headers         map[string]string
	FollowRedirects bool
	MaxRedirects    int // Maximum number of redirects to follow (default: 10, 0 = no limit)
	EnableHTTP2     bool
	EnableCookies   bool
}

Config defines the HTTP client configuration.

Thread Safety: Config must be treated as immutable after passing it to New(). Do not modify Config fields after client creation. Create a new Config for each client with different settings.

func DefaultConfig

func DefaultConfig() *Config

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

func SecureConfig added in v1.1.0

func SecureConfig() *Config

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.

type DomainClient added in v1.3.0

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

DomainClient provides automatic Cookie and Header management for a specific domain. All methods are safe for concurrent use by multiple goroutines.

Features: - Automatic Cookie persistence across requests - Automatic Header persistence across requests - Per-request overrides via WithCookies/WithHeaderMap - Thread-safe state management

Example:

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

// First request with initial cookies and headers
resp1, _ := client.Get("/",
    httpc.WithCookies(initialCookies),
    httpc.WithHeaderMap(map[string]string{"User-Agent": "MyBot"}),
)

// Second request automatically uses cookies from resp1 and persisted headers
// Can override with new headers
resp2, _ := client.Get("/search?q=test",
    httpc.WithHeaderMap(map[string]string{"Accept": "application/json"}),
)

func NewDomain added in v1.3.0

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

NewDomain creates a new DomainClient for the specified base URL. The base URL should include the scheme and domain (e.g., "https://www.example.com"). Returns an error if the URL is invalid or the client cannot be created.

The client automatically manages: - Cookies: Saved from responses, sent in subsequent requests - Headers: Persisted across requests unless overridden

Example:

client, err := httpc.NewDomain("https://api.example.com")
if err != nil {
    log.Fatal(err)
}
defer client.Close()

func (*DomainClient) ClearCookies added in v1.3.0

func (dc *DomainClient) ClearCookies()

ClearCookies removes all persistent cookies.

func (*DomainClient) ClearHeaders added in v1.3.0

func (dc *DomainClient) ClearHeaders()

ClearHeaders removes all persistent headers.

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 executes a DELETE request with automatic Cookie and Header management.

func (*DomainClient) DeleteCookie added in v1.3.0

func (dc *DomainClient) DeleteCookie(name string)

DeleteCookie removes a persistent cookie by name.

func (*DomainClient) DeleteHeader added in v1.3.0

func (dc *DomainClient) DeleteHeader(key string)

DeleteHeader removes a persistent header.

func (*DomainClient) Get added in v1.3.0

func (dc *DomainClient) Get(path string, options ...RequestOption) (*Result, error)

Get executes a GET request with automatic Cookie and Header management.

func (*DomainClient) GetCookie added in v1.3.0

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

GetCookie returns a specific persistent cookie by name. Returns nil if the cookie doesn't exist.

func (*DomainClient) GetCookies added in v1.3.0

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

GetCookies returns a copy of all persistent cookies.

func (*DomainClient) GetHeaders added in v1.3.0

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

GetHeaders returns a copy of all persistent headers.

func (*DomainClient) Head added in v1.3.0

func (dc *DomainClient) Head(path string, options ...RequestOption) (*Result, error)

Head executes a HEAD request with automatic Cookie and Header management.

func (*DomainClient) Options added in v1.3.0

func (dc *DomainClient) Options(path string, options ...RequestOption) (*Result, error)

Options executes an OPTIONS request with automatic Cookie and Header management.

func (*DomainClient) Patch added in v1.3.0

func (dc *DomainClient) Patch(path string, options ...RequestOption) (*Result, error)

Patch executes a PATCH request with automatic Cookie and Header management.

func (*DomainClient) Post added in v1.3.0

func (dc *DomainClient) Post(path string, options ...RequestOption) (*Result, error)

Post executes a POST request with automatic Cookie and Header management.

func (*DomainClient) Put added in v1.3.0

func (dc *DomainClient) Put(path string, options ...RequestOption) (*Result, error)

Put executes a PUT request with automatic Cookie and Header management.

func (*DomainClient) SetCookie added in v1.3.0

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

SetCookie sets a persistent cookie that will be sent with all subsequent requests. This cookie can be overridden per-request using WithCookie or WithCookies.

func (*DomainClient) SetCookies added in v1.3.0

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

SetCookies sets multiple persistent cookies.

func (*DomainClient) SetHeader added in v1.3.0

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

SetHeader sets a persistent header that will be sent with all subsequent requests. This header can be overridden per-request using WithHeader or WithHeaderMap.

func (*DomainClient) SetHeaders added in v1.3.0

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

SetHeaders sets multiple persistent headers.

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 FileData

type FileData struct {
	Filename    string
	Content     []byte
	ContentType string
}

type FormData

type FormData struct {
	Fields map[string]string
	Files  map[string]*FileData
}

type HTTPError

type HTTPError struct {
	StatusCode int
	Status     string
	URL        string
	Method     string
	Body       string
}

HTTPError represents an HTTP error response

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Request

type Request struct {
	Method          string
	URL             string
	Headers         map[string]string
	QueryParams     map[string]any
	Body            any
	Timeout         time.Duration
	MaxRetries      int
	Context         context.Context
	Cookies         []http.Cookie
	FollowRedirects *bool // Override client's FollowRedirects setting (nil = use client default)
	MaxRedirects    *int  // Override client's MaxRedirects setting (nil = use client default)
}

type RequestInfo added in v1.3.0

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

RequestInfo contains information about the HTTP request that was sent.

type RequestMeta added in v1.3.0

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

RequestMeta contains metadata about the request execution.

type RequestOption

type RequestOption func(*Request) error

func WithAccept

func WithAccept(accept string) RequestOption

WithAccept sets the Accept header for the request.

func WithBasicAuth

func WithBasicAuth(username, password string) RequestOption

WithBasicAuth adds HTTP Basic Authentication to the request. The credentials are base64-encoded and added to the Authorization header. Validates credentials to prevent injection attacks and enforce size limits. Returns an error if username is empty or credentials contain invalid characters.

func WithBearerToken

func WithBearerToken(token string) RequestOption

WithBearerToken adds a Bearer token to the Authorization header. Validates token to prevent injection attacks and enforce size limits. Returns an error if token is empty, too long, or contains invalid characters.

func WithBinary

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

func WithBody

func WithBody(body any) RequestOption

func WithContentType

func WithContentType(contentType string) RequestOption

WithContentType sets the Content-Type header for the request.

func WithContext

func WithContext(ctx context.Context) RequestOption

func WithCookie

func WithCookie(cookie http.Cookie) RequestOption

func WithCookieString added in v1.3.0

func WithCookieString(cookieString string) RequestOption

WithCookieString parses a cookie string and adds all cookies to the request. The cookie string should be in the format: "name1=value1; name2=value2; name3=value3" This is commonly used when copying cookies from browser developer tools or server responses. Each cookie is created with secure defaults: HttpOnly=true, SameSite=Lax. Returns an error if the cookie string is malformed or contains invalid cookie names/values.

Example:

WithCookieString("BPSID=4418ECBB1281B550; PSTM=1733760779; BDS=kUwNTVFcEUBUItoc")

func WithCookieValue

func WithCookieValue(name, value string) RequestOption

WithCookieValue adds a cookie with the given name and value to the request. The cookie is created with secure defaults: HttpOnly=true, SameSite=Lax. The domain should be set explicitly using WithCookie if needed. For HTTPS requests, consider using WithCookie with Secure=true. Returns an error if name is empty or contains invalid characters.

func WithCookies

func WithCookies(cookies []http.Cookie) RequestOption

func WithFile

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

WithFile adds a file upload to the request. Returns an error if fieldName or filename is empty or contains invalid characters.

func WithFollowRedirects added in v1.3.0

func WithFollowRedirects(follow bool) RequestOption

WithFollowRedirects enables or disables automatic redirect following for this request. This overrides the client's FollowRedirects configuration. When disabled, the client returns the redirect response (3xx) without following it.

func WithForm

func WithForm(data map[string]string) RequestOption

func WithFormData

func WithFormData(data *FormData) RequestOption

func WithHeader

func WithHeader(key, value string) RequestOption

WithHeader adds a custom header to the request. Returns an error if the header key or value is invalid.

func WithHeaderMap

func WithHeaderMap(headers map[string]string) RequestOption

WithHeaderMap adds multiple headers to the request. Returns an error if any header key or value is invalid.

func WithJSON

func WithJSON(data any) RequestOption

WithJSON sets the request body to JSON-encoded data and sets Content-Type to application/json.

func WithJSONAccept

func WithJSONAccept() RequestOption

WithJSONAccept sets the Accept header to application/json.

func WithMaxRedirects added in v1.3.0

func WithMaxRedirects(maxRedirects int) RequestOption

WithMaxRedirects sets the maximum number of redirects to follow for this request. This overrides the client's MaxRedirects configuration. Set to 0 to allow unlimited redirects (not recommended). Returns an error if maxRedirects is negative or exceeds 50.

func WithMaxRetries

func WithMaxRetries(maxRetries int) RequestOption

WithMaxRetries sets the maximum number of retry attempts. Returns ErrInvalidRetry if maxRetries is not between 0 and 10.

func WithQuery

func WithQuery(key string, value any) RequestOption

WithQuery adds a single query parameter to the request URL. Returns an error if key is empty, too long, or contains invalid characters.

func WithQueryMap

func WithQueryMap(params map[string]any) RequestOption

WithQueryMap adds multiple query parameters to the request URL. Returns an error if any key is empty, too long, or contains invalid characters.

func WithText

func WithText(content string) RequestOption

func WithTimeout

func WithTimeout(timeout time.Duration) RequestOption

WithTimeout sets the request timeout. Returns ErrInvalidTimeout if timeout is negative or exceeds 30 minutes.

func WithUserAgent

func WithUserAgent(userAgent string) RequestOption

WithUserAgent sets the User-Agent header for the request.

func WithXML

func WithXML(data any) RequestOption

WithXML sets the request body to XML-encoded data and sets Content-Type to application/xml.

func WithXMLAccept

func WithXMLAccept() RequestOption

WithXMLAccept sets the Accept header to application/xml.

type ResponseInfo added in v1.3.0

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

ResponseInfo contains the HTTP response data received from the server.

type Result added in v1.3.0

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

Result represents the complete outcome of an HTTP request. It provides clear separation between request information, response data, and metadata.

Thread Safety: Result objects are immutable after creation and safe to read from multiple goroutines concurrently. Do not modify Result fields directly.

func Delete

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

Delete executes a DELETE request using the default client and returns a Result.

func Get

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

Get executes a GET request using the default client and returns a Result.

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

Head executes a HEAD request using the default client and returns a Result.

func Options

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

Options executes an OPTIONS request using the default client and returns a Result.

func Patch

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

Patch executes a PATCH request using the default client and returns a Result.

func Post

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

Post executes a POST request using the default client and returns a Result.

func Put

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

Put executes a PUT request using the default client and returns a Result.

func (*Result) Body added in v1.3.0

func (r *Result) Body() string

Body returns the response body as a string. This is a convenience method equivalent to accessing Result.Response.Body.

func (*Result) GetCookie added in v1.3.0

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

GetCookie returns a specific cookie from the response by name. This returns cookies from the server's Set-Cookie header (response cookies).

func (*Result) GetRequestCookie added in v1.3.0

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

GetRequestCookie returns a specific cookie from the request by name.

func (*Result) HasCookie added in v1.3.0

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

HasCookie checks if a specific cookie exists in the response.

func (*Result) HasRequestCookie added in v1.3.0

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

HasRequestCookie checks if a specific cookie was sent in the request.

func (*Result) Html added in v1.3.0

func (r *Result) Html() string

Html returns the response body as HTML content. This is an alias for Body() method.

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) JSON added in v1.3.0

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

JSON unmarshals the response body into the provided interface. Returns ErrResponseBodyEmpty if the body is nil or empty. Returns ErrResponseBodyTooLarge if the body exceeds 50MB.

func (*Result) RawBody added in v1.3.0

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

RawBody returns the response body as raw bytes. This is a convenience method equivalent to accessing Result.Response.RawBody.

func (*Result) RequestCookies added in v1.3.0

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

RequestCookies returns the cookies that were sent with the request. This is a convenience method equivalent to accessing Result.Request.Cookies.

func (*Result) ResponseCookies added in v1.3.0

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

ResponseCookies returns the cookies received in the response. This is a convenience method equivalent to accessing Result.Response.Cookies.

func (*Result) SaveToFile added in v1.3.0

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

SaveToFile saves the response body to a file. Returns ErrResponseBodyEmpty if the body is nil or empty.

func (*Result) StatusCode added in v1.3.0

func (r *Result) StatusCode() int

StatusCode returns the HTTP status code. This is a convenience method equivalent to accessing Result.Response.StatusCode.

func (*Result) String added in v1.3.0

func (r *Result) String() string

String returns a formatted string representation of the result.

Directories

Path Synopsis
examples
internal

Jump to

Keyboard shortcuts

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