httpclient

package module
v1.8.1 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2025 License: MIT Imports: 8 Imported by: 1

README

http-client

Fluent HTTP client for Go with streaming support and zero dependencies.

Features

  • Fluent API with method chaining
  • Path variables with {placeholder} syntax
  • Streaming for large payloads via io.Pipe
  • Context-aware with proper cancellation handling
  • Multipart/form-data file uploads
  • Type-safe methods for parameters
  • Built-in middleware for retry, rate limiting, and logging
  • Zero third-party dependencies

Installation

go get github.com/nativebpm/http-client

Quick Start

client, _ := httpclient.NewClient(&http.Client{}, "https://api.example.com")

// Simple GET
resp, err := client.GET(ctx, "/users").Send()

// POST with JSON
resp, err = client.POST(ctx, "/users").
    JSON(map[string]string{"name": "John"}).
    Send()

// Path variables
resp, err = client.GET(ctx, "/users/{id}").
    PathInt("id", 123).
    Send()

// Multipart upload
resp, err = client.Multipart(ctx, "/upload").
    File("document", "file.pdf", fileReader).
    Send()

API

Client Methods
GET(ctx, path string) *Request
POST(ctx, path string) *Request
PUT(ctx, path string) *Request
PATCH(ctx, path string) *Request
DELETE(ctx, path string) *Request
Request(ctx, method, path string) *Request
Multipart(ctx, path string) *Multipart
Request Builder
Header(key, value string)           // Set header
PathParam(key, value string)        // Replace {key} in path
PathInt(key string, value int)      // Path param as int
PathBool(key string, value bool)    // Path param as bool
PathFloat(key string, value float64) // Path param as float
Param(key, value string)            // Query parameter
Int(key string, value int)          // Query param as int
Bool(key string, value bool)        // Query param as bool
Float(key string, value float64)    // Query param as float
JSON(data any)                      // JSON body
Body(body io.ReadCloser, contentType string) // Custom body
Timeout(duration time.Duration)     // Request timeout
Send() (*http.Response, error)      // Execute request
Multipart Builder

Same as Request, plus:

File(key, filename string, content io.Reader) // Add file

Middleware

The client supports middleware for intercepting and modifying requests/responses. Middleware are functions that wrap http.RoundTripper.

Fluent Builder Methods

For convenience, the client provides fluent methods for common middleware:

client, _ := httpclient.NewClient(&http.Client{}, "https://api.example.com")

// Add retry with default config
client.WithRetry()

// Add retry with custom config
client.WithRetryConfig(httpclient.RetryConfig{
    MaxRetries: 5,
    Backoff: func(attempt int) time.Duration {
        return time.Duration(attempt*2) * time.Second
    },
})

// Add rate limiting (10 requests per minute)
client.WithRateLimit(10, time.Minute/10)

// Add logging
client.WithLogging()

// Add circuit breaker with default config
client.WithCircuitBreaker()

// Add circuit breaker with custom config
client.WithCircuitBreakerConfig(httpclient.CircuitBreakerConfig{
    FailureThreshold: 3,
    SuccessThreshold: 1,
    Timeout: 5 * time.Second,
})

// Chain them
client.WithRetry().WithRateLimit(5, time.Second).WithLogging().WithCircuitBreaker()
Custom Middleware
client.Use(func(next http.RoundTripper) http.RoundTripper {
    return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
        // Pre-request logic
        resp, err := next.RoundTrip(req)
        // Post-response logic
        return resp, err
    })
})
Built-in Middleware Functions

You can also use the middleware functions directly:

import "github.com/nativebpm/http-client"

// Retry
client.Use(httpclient.RetryMiddleware(httpclient.DefaultRetryConfig()))

// Rate limiting
limiter := httpclient.NewSimpleRateLimiter(10, time.Minute/10)
client.Use(httpclient.RateLimitMiddleware(limiter))

// Logging
client.Use(httpclient.LoggingMiddleware())

// Circuit breaker
cb := httpclient.NewCircuitBreaker(httpclient.DefaultCircuitBreakerConfig())
client.Use(httpclient.CircuitBreakerMiddleware(cb))

See examples/ for complete working examples.

Examples

See the examples/ directory for complete working examples, including middleware usage.

Path Variables
// Single parameter
client.GET(ctx, "/users/{id}").PathParam("id", "123").Send()
// → GET /users/123

// Multiple parameters
client.POST(ctx, "/api/{version}/users/{id}").
    PathParam("version", "v1").
    PathInt("id", 123).
    Send()
// → POST /api/v1/users/123

// Mixed with query params
client.GET(ctx, "/users/{id}/posts").
    PathInt("id", 123).
    Param("page", "2").
    Send()
// → GET /users/123/posts?page=2
File Uploads
// Single file
client.Multipart(ctx, "/upload").
    File("document", "report.pdf", fileReader).
    Send()

// Multiple files with params
client.Multipart(ctx, "/users/{id}/documents").
    PathInt("id", 123).
    Param("category", "invoices").
    File("file1", "doc1.pdf", reader1).
    File("file2", "doc2.pdf", reader2).
    Send()
Timeouts
// Method timeout
client.POST(ctx, "/slow").
    Timeout(30 * time.Second).
    JSON(data).
    Send()

// Context timeout
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
client.POST(ctx, "/slow").JSON(data).Send()
Use Cases

Testing

go test ./...

License

MIT

Documentation

Overview

Package httpclient provides a convenient HTTP client with request builders.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CircuitBreakerMiddleware added in v1.8.1

func CircuitBreakerMiddleware(cb *CircuitBreaker) func(http.RoundTripper) http.RoundTripper

CircuitBreakerMiddleware returns a middleware that implements circuit breaker

func LoggingMiddleware added in v1.8.1

func LoggingMiddleware() func(http.RoundTripper) http.RoundTripper

LoggingMiddleware returns a middleware that logs requests and responses

func RateLimitMiddleware added in v1.8.1

func RateLimitMiddleware(limiter *RateLimiter) func(http.RoundTripper) http.RoundTripper

RateLimitMiddleware returns a middleware that enforces rate limiting

func RetryMiddleware added in v1.8.1

func RetryMiddleware(config RetryConfig) func(http.RoundTripper) http.RoundTripper

RetryMiddleware returns a middleware that retries requests based on the config

Types

type CircuitBreaker added in v1.8.1

type CircuitBreaker = middleware.CircuitBreaker

CircuitBreaker implements a simple circuit breaker

func NewCircuitBreaker added in v1.8.1

func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

type CircuitBreakerConfig added in v1.8.1

type CircuitBreakerConfig = middleware.CircuitBreakerConfig

CircuitBreakerConfig holds configuration for circuit breaker middleware

func DefaultCircuitBreakerConfig added in v1.8.1

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns a default circuit breaker configuration

type CircuitBreakerState added in v1.8.1

type CircuitBreakerState = middleware.CircuitBreakerState

CircuitBreakerState represents the state of the circuit breaker

type Client

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

Client wraps http.Client and provides request builders for different HTTP methods.

func NewClient

func NewClient(client *http.Client, baseURL string) (*Client, error)

NewClient creates a new HTTP client with the given base URL. Returns an error if the base URL is invalid.

func (*Client) DELETE added in v1.6.0

func (c *Client) DELETE(ctx context.Context, path string) *request.Request

DELETE creates a DELETE request builder.

func (*Client) GET added in v1.6.0

func (c *Client) GET(ctx context.Context, path string) *request.Request

GET creates a GET request builder.

func (*Client) Multipart added in v1.6.0

func (c *Client) Multipart(ctx context.Context, path string) *formdata.Multipart

Multipart creates a multipart/form-data POST request builder.

func (*Client) MultipartRequest added in v1.8.1

func (c *Client) MultipartRequest(ctx context.Context, path, method string) *formdata.Multipart

MultipartRequest creates a multipart/form-data request builder with HTTP method.

func (*Client) PATCH added in v1.6.0

func (c *Client) PATCH(ctx context.Context, path string) *request.Request

PATCH creates a PATCH request builder.

func (*Client) POST added in v1.6.0

func (c *Client) POST(ctx context.Context, path string) *request.Request

POST creates a POST request builder.

func (*Client) PUT added in v1.6.0

func (c *Client) PUT(ctx context.Context, path string) *request.Request

PUT creates a PUT request builder.

func (*Client) Request added in v1.6.0

func (c *Client) Request(ctx context.Context, method, path string) *request.Request

Request creates a standard HTTP request builder.

func (*Client) SetTransport added in v1.8.1

func (c *Client) SetTransport(rt http.RoundTripper) *Client

SetTransport sets a custom base RoundTripper. This will be wrapped by middlewares.

func (*Client) Use added in v1.8.1

func (c *Client) Use(middleware func(http.RoundTripper) http.RoundTripper) *Client

Use adds a middleware to the client. Middlewares are applied in the order they are added. Each middleware is a function that takes a RoundTripper and returns a wrapped RoundTripper.

func (*Client) WithCircuitBreaker added in v1.8.1

func (c *Client) WithCircuitBreaker() *Client

WithCircuitBreaker adds circuit breaker middleware with default config

func (*Client) WithCircuitBreakerConfig added in v1.8.1

func (c *Client) WithCircuitBreakerConfig(config CircuitBreakerConfig) *Client

WithCircuitBreakerConfig adds circuit breaker middleware with custom config

func (*Client) WithLogging added in v1.8.1

func (c *Client) WithLogging() *Client

WithLogging adds logging middleware

func (*Client) WithRateLimit added in v1.8.1

func (c *Client) WithRateLimit(capacity int, refillRate time.Duration) *Client

WithRateLimit adds rate limiting middleware

func (*Client) WithRetry added in v1.8.1

func (c *Client) WithRetry() *Client

WithRetry adds retry middleware with default config

func (*Client) WithRetryConfig added in v1.8.1

func (c *Client) WithRetryConfig(config RetryConfig) *Client

WithRetryConfig adds retry middleware with custom config

type Multipart added in v1.1.0

type Multipart = formdata.Multipart

Public types re-exports

type RateLimiter added in v1.8.1

type RateLimiter = middleware.RateLimiter

RateLimiter implements a basic token bucket rate limiter

func NewSimpleRateLimiter added in v1.8.1

func NewSimpleRateLimiter(capacity int, refillRate time.Duration) *RateLimiter

NewSimpleRateLimiter creates a new rate limiter

type Request

type Request = request.Request

type RetryConfig added in v1.8.1

type RetryConfig = middleware.RetryConfig

RetryConfig holds configuration for retry middleware

func DefaultRetryConfig added in v1.8.1

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a default retry configuration

Directories

Path Synopsis
examples
retry_example command
internal

Jump to

Keyboard shortcuts

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