httpc

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2025 License: MIT Imports: 15 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

This section is empty.

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.

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes formats bytes in human-readable format (e.g., "1.50 KB", "2.30 MB")

func FormatSpeed

func FormatSpeed(bytesPerSecond float64) string

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

func NewCookieJar

func NewCookieJar() (http.CookieJar, error)

func SetDefaultClient

func SetDefaultClient(client Client) error

func ValidateConfig added in v1.1.0

func ValidateConfig(cfg *Config) error

ValidateConfig validates the configuration with reasonable limits.

Types

type Client

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

	// Generic request method
	Request(ctx context.Context, method, url string, options ...RequestOption) (*Response, error)

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

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

func NewPerformance added in v1.1.0

func NewPerformance() (Client, error)

func NewSecure added in v1.1.0

func NewSecure() (Client, error)

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. Config should be treated as immutable after passing it to New().

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
}

func DefaultDownloadOptions

func DefaultDownloadOptions(filePath string) *DownloadOptions

type DownloadProgressCallback

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

type DownloadResult

type DownloadResult struct {
	FilePath      string
	BytesWritten  int64
	Duration      time.Duration
	AverageSpeed  float64
	StatusCode    int
	ContentLength int64
	Resumed       bool
}

func DownloadFile

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

func DownloadWithOptions

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

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
}

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

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

type Response struct {
	StatusCode    int
	Status        string
	Headers       http.Header // Deep-copied for thread safety
	Body          string
	RawBody       []byte
	ContentLength int64
	Duration      time.Duration
	Attempts      int
	Cookies       []*http.Cookie
}

Response represents an HTTP response. Response objects are safe to read from multiple goroutines after they are returned. The Headers map is deep-copied to prevent concurrent access issues.

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

GetCookie returns the named cookie from the response or nil if not found

func (*Response) HasCookie

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

HasCookie returns true if the response contains a cookie with the given name

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.

func (*Response) SaveToFile

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

Directories

Path Synopsis
examples
internal

Jump to

Keyboard shortcuts

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