httpc

package module
v1.3.5 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 19 Imported by: 0

README

# HTTPC - Production-Ready HTTP Client for Go

Go Version pkg.go.dev 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


✨ Core Features

  • 🛡️ 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

📦 Installation

go get -u github.com/cybergodev/httpc

🚀 Quick Start

package main

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

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

    // POST with JSON and authentication
    user := map[string]string{"name": "John", "email": "[email protected]"}
    result, 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", result.Body())
}

Default Request Headers: By default, use "httpc.DefaultConfig()", which automatically includes a User-Agent: httpc/1.0 header with all requests. To customize default headers:

  • User-Agent: Set config.UserAgent or use httpc.WithUserAgent("your-custom-agent")
  • Custom Headers: Set config.Headers map when creating a client for client-level default headers
  • Per-Request: Use httpc.WithHeader() or httpc.WithHeaderMap() to override for specific requests

📖 See more examples | 🚀 Getting Started Guide

📖 Core Features

HTTP Methods

All standard HTTP methods with clean, intuitive API:

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

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

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

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

// DELETE - Remove resource
result, 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.WithXML(data)               // XML body
httpc.WithForm(formData)          // Form data
httpc.WithText("content")         // Plain text
httpc.WithBinary(data, "image/png")  // Binary data with content type
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
result, 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("Request Headers: %v\n", request.Headers)
fmt.Printf("Request Cookies: %v\n", request.Cookies)

// 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")
if result.HasCookie("session_id") {
    fmt.Println("Session cookie found")
}

// Access request cookies
requestCookies := result.RequestCookies()
requestCookie := result.GetRequestCookie("auth_token")

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

// Save response to file
err = result.SaveToFile("response.html")

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
// Note: HTTPC returns Result for all status codes (including 4xx and 5xx)
// HTTPError is NOT automatically returned for non-2xx status codes
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
// Note: EnableCookies is false by default in DefaultConfig()
config := httpc.DefaultConfig()
config.EnableCookies = true  // Must explicitly enable for automatic cookie handling
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()

// Request Homepage
resp0, err := client.Get("/")

// First request - server sets cookies
resp1, err := client.Post("/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": "[email protected]",
        "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

File Downloads with DomainClient:

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

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

// Simple download with automatic state management
result, err := client.DownloadFile("/files/report.pdf", "downloads/report.pdf")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Downloaded: %s at %s/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 = client.DownloadWithOptions("/files/large-file.zip", opts)

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
  • File Download Support - Download files with automatic state management (cookies/headers)
  • 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.

📖 Security Guide

Documentation

Guides

Examples

🤝 Contributing

Contributions, issue reports, and suggestions are welcome!

📄 License

MIT License - See LICENSE file for details.


Crafted with care for the Go community ❤️ | 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")
)

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

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
}

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.

func NewPerformance added in v1.1.0

func NewPerformance() (Client, error)

NewPerformance creates a new client optimized for high-throughput scenarios.

func NewSecure added in v1.1.0

func NewSecure() (Client, error)

NewSecure creates a new client with security-focused configuration.

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
	StrictContentLength bool

	MaxRetries    int
	RetryDelay    time.Duration
	BackoffFactor float64

	UserAgent       string
	Headers         map[string]string
	FollowRedirects bool
	MaxRedirects    int
	EnableHTTP2     bool
	EnableCookies   bool
}

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
}

func NewDomain added in v1.3.0

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

func (*DomainClient) ClearCookies added in v1.3.0

func (dc *DomainClient) ClearCookies()

func (*DomainClient) ClearHeaders added in v1.3.0

func (dc *DomainClient) ClearHeaders()

func (*DomainClient) Close added in v1.3.0

func (dc *DomainClient) Close() error

func (*DomainClient) Delete added in v1.3.0

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

func (*DomainClient) DeleteCookie added in v1.3.0

func (dc *DomainClient) DeleteCookie(name string)

func (*DomainClient) DeleteHeader added in v1.3.0

func (dc *DomainClient) DeleteHeader(key string)

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 given path to the specified file path. The path is relative to the domain's base URL or can be a full URL. Automatic state management (cookies/headers) is applied during download.

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. The path is relative to the domain's base URL or can be a full URL. Automatic state management (cookies/headers) is applied during download.

func (*DomainClient) Get added in v1.3.0

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

func (*DomainClient) GetCookie added in v1.3.0

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

func (*DomainClient) GetCookies added in v1.3.0

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

func (*DomainClient) GetHeaders added in v1.3.0

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

func (*DomainClient) Head added in v1.3.0

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

func (*DomainClient) Options added in v1.3.0

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

func (*DomainClient) Patch added in v1.3.0

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

func (*DomainClient) Post added in v1.3.0

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

func (*DomainClient) Put added in v1.3.0

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

func (*DomainClient) SetCookie added in v1.3.0

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

func (*DomainClient) SetCookies added in v1.3.0

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

func (*DomainClient) SetHeader added in v1.3.0

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

func (*DomainClient) SetHeaders added in v1.3.0

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

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 {
	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 RequestOption

type RequestOption func(*Request) error

func WithAccept

func WithAccept(accept string) RequestOption

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 WithContentType

func WithContentType(contentType string) RequestOption

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

func WithCookieValue

func WithCookieValue(name, value string) RequestOption

func WithCookies

func WithCookies(cookies []http.Cookie) 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

func WithJSON

func WithJSON(data any) RequestOption

func WithJSONAccept

func WithJSONAccept() RequestOption

func WithMaxRedirects added in v1.3.0

func WithMaxRedirects(maxRedirects int) RequestOption

func WithMaxRetries

func WithMaxRetries(maxRetries int) RequestOption

func WithQuery

func WithQuery(key string, value any) RequestOption

func WithQueryMap

func WithQueryMap(params map[string]any) RequestOption

func WithText

func WithText(content string) RequestOption

func WithTimeout

func WithTimeout(timeout time.Duration) RequestOption

func WithUserAgent

func WithUserAgent(userAgent string) RequestOption

func WithXML

func WithXML(data any) RequestOption

func WithXMLAccept

func WithXMLAccept() RequestOption

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
}

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 (*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) Html added in v1.3.0

func (r *Result) Html() string

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

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

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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