httpc

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2025 License: MIT Imports: 16 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

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

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

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

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

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

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

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

resp, 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 !resp.IsSuccess() {
    return fmt.Errorf("unexpected status: %d", resp.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()
resp, 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
resp, err := httpc.Get(url, httpc.WithMaxRetries(5))

Context Support

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

// Cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
    time.Sleep(5 * time.Second)
    cancel()
}()
resp, err := client.Get(url, httpc.WithContext(ctx))
// 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")

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()
        resp, _ := 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 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. Returns ErrNilConfig if cfg is nil. Returns ErrInvalidTimeout if timeout is negative or exceeds 30 minutes. Returns ErrInvalidRetry if retry configuration is invalid. Returns ErrInvalidHeader if any header is invalid.

Types

type Client

type Client interface {
	Get(url string, options ...RequestOption) (*Response, error)
	Post(url string, options ...RequestOption) (*Response, error)
	Put(url string, options ...RequestOption) (*Response, error)
	Patch(url string, options ...RequestOption) (*Response, error)
	Delete(url string, options ...RequestOption) (*Response, error)
	Head(url string, options ...RequestOption) (*Response, error)
	Options(url string, options ...RequestOption) (*Response, error)

	Request(ctx context.Context, method, url string, options ...RequestOption) (*Response, 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
	StrictContentLength bool

	MaxRetries    int
	RetryDelay    time.Duration
	BackoffFactor float64

	UserAgent       string
	Headers         map[string]string
	FollowRedirects bool
	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 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
}

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

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

Response represents an HTTP response.

Thread Safety: Response objects are immutable after creation and safe to read from multiple goroutines concurrently. All methods are goroutine-safe. Do not modify Response fields directly.

func Delete

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

Delete executes a DELETE request using the default client

func Get

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

Get executes a GET request using the default client

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

Head executes a HEAD request using the default client

func Options

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

Options executes an OPTIONS request using the default client

func Patch

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

Patch executes a PATCH request using the default client

func Post

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

Post executes a POST request using the default client

func Put

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

Put executes a PUT request using the default client

func (*Response) GetCookie

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

func (*Response) HasCookie

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

func (*Response) Html added in v1.2.2

func (r *Response) Html() string

Html is an alias method for the r.Body property

func (*Response) IsClientError

func (r *Response) IsClientError() bool

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

func (*Response) IsRedirect

func (r *Response) IsRedirect() bool

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

func (*Response) IsServerError

func (r *Response) IsServerError() bool

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

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

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

func (*Response) JSON

func (r *Response) 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 (*Response) SaveToFile

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

func (*Response) String added in v1.2.2

func (r *Response) String() string

String returns a formatted string representation of the response. Includes status code, status text, content length, duration, and attempts.

Directories

Path Synopsis
examples
internal

Jump to

Keyboard shortcuts

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