httpclient

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: MIT Imports: 15 Imported by: 0

README

go-httpclient

Go Version License Go Report Card GoDoc

A production-ready HTTP client for Go with built-in resilience patterns including retry policies, circuit breakers, timeouts, and fallback mechanisms. Perfect for building reliable microservices and external API integrations.

Features

Resilience Patterns

  • 🔄 Retry Policy - Exponential backoff, jitter, max attempts/duration
  • Circuit Breaker - Prevent cascading failures with automatic recovery
  • ⏱️ Timeout - Request-level and global timeout controls
  • 🛡️ Fallback - Graceful degradation with custom fallback responses

🎯 Developer Experience

  • Simple, intuitive API with method chaining
  • JSON marshaling/unmarshaling built-in
  • Context support for cancellation and deadlines
  • Typed error handling with detailed context
  • Comprehensive test coverage (>95%)

🏗️ Production Ready

  • Built on failsafe-go - battle-tested resilience library
  • Clean Architecture principles
  • Zero external dependencies (except failsafe-go)
  • Fully documented with examples

Installation

go get github.com/ja7ad/httpclient

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewResilientClient

func NewResilientClient(cfg *ResilienceConfig) *http.Client

NewResilientClient creates an HTTP client with resilience policies This is the recommended way to create a resilient HTTP client

func NewResilientTransport

func NewResilientTransport(baseTransport http.RoundTripper, cfg *ResilienceConfig) http.RoundTripper

NewResilientTransport wraps an existing transport with resilience policies Use this if you need to customize the base transport

Types

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Enabled               bool
	FailureThreshold      uint            // Count-based: Opens after N consecutive failures
	FailureThresholdRatio *ThresholdRatio // Ratio-based: Opens when X of Y executions fail
	SuccessThreshold      uint            // Count-based: Closes after N consecutive successes in half-open
	SuccessThresholdRatio *ThresholdRatio // Ratio-based: Closes when X of Y executions succeed in half-open
	Delay                 time.Duration   // Time to wait in open state before half-opening
	OnStateChanged        func(event circuitbreaker.StateChangedEvent)
	OnOpen                func(event circuitbreaker.StateChangedEvent)
	OnHalfOpen            func(event circuitbreaker.StateChangedEvent)
	OnClose               func(event circuitbreaker.StateChangedEvent)
}

CircuitBreakerConfig holds circuit breaker configuration

type Client

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

func NewClient

func NewClient(opts ...ClientOption) *Client

func NewDefaultClient

func NewDefaultClient(baseURL string) *Client

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string) (*http.Response, error)

func (*Client) DeleteJSON

func (c *Client) DeleteJSON(ctx context.Context, path string, result interface{}) error

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body interface{}) (*http.Response, error)

func (*Client) DoWithResponse

func (c *Client) DoWithResponse(ctx context.Context, method, path string, body, result interface{}) error

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string) (*http.Response, error)

func (*Client) GetHTTPClient

func (c *Client) GetHTTPClient() *http.Client

func (*Client) GetJSON

func (c *Client) GetJSON(ctx context.Context, path string, result interface{}) error

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, body interface{}) (*http.Response, error)

func (*Client) PatchJSON

func (c *Client) PatchJSON(ctx context.Context, path string, body, result interface{}) error

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body interface{}) (*http.Response, error)

func (*Client) PostJSON

func (c *Client) PostJSON(ctx context.Context, path string, body, result interface{}) error

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body interface{}) (*http.Response, error)

func (*Client) PutJSON

func (c *Client) PutJSON(ctx context.Context, path string, body, result interface{}) error

func (*Client) RemoveHeader

func (c *Client) RemoveHeader(key string)

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string)

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(httpClient *http.Client)

func (*Client) SetHeader

func (c *Client) SetHeader(key, value string)

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string)

type ClientOption

type ClientOption func(*Client)

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

func WithHeader

func WithHeader(key, value string) ClientOption

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

func WithResilienceConfig

func WithResilienceConfig(cfg *ResilienceConfig) ClientOption

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

type Error

type Error struct {
	Type       ErrorType
	Message    string
	StatusCode int
	URL        string
	Method     string
	RequestID  string
	Err        error
	Timestamp  time.Time
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorType

type ErrorType string
const (
	ErrorTypeTimeout        ErrorType = "timeout"
	ErrorTypeNetwork        ErrorType = "network"
	ErrorTypeHTTP           ErrorType = "http"
	ErrorTypeRetryExhausted ErrorType = "retry_exhausted"
	ErrorTypeValidation     ErrorType = "validation"
	ErrorTypeUnknown        ErrorType = "unknown"
)

type FallbackConfig

type FallbackConfig struct {
	Enabled            bool
	FallbackFunc       func(exec failsafe.Execution[*http.Response]) (*http.Response, error)
	OnFallbackExecuted func(event failsafe.ExecutionDoneEvent[*http.Response])
}

FallbackConfig holds fallback configuration

type ResilienceBuilder

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

ResilienceBuilder builds resilience configurations using fluent API

func NewResilienceBuilder

func NewResilienceBuilder() *ResilienceBuilder

NewResilienceBuilder creates a new resilience configuration builder

func (*ResilienceBuilder) Build

func (rb *ResilienceBuilder) Build() *ResilienceConfig

Build constructs the final resilience configuration

func (*ResilienceBuilder) WithCircuitBreaker

func (rb *ResilienceBuilder) WithCircuitBreaker(cfg *CircuitBreakerConfig) *ResilienceBuilder

WithCircuitBreaker configures circuit breaker settings

func (*ResilienceBuilder) WithFallback

func (rb *ResilienceBuilder) WithFallback(cfg *FallbackConfig) *ResilienceBuilder

WithFallback configures fallback settings

func (*ResilienceBuilder) WithRetryPolicy

func (rb *ResilienceBuilder) WithRetryPolicy(cfg *RetryPolicyConfig) *ResilienceBuilder

WithRetryPolicy configures retry policy settings

func (*ResilienceBuilder) WithTimeout

func (rb *ResilienceBuilder) WithTimeout(cfg *TimeoutConfig) *ResilienceBuilder

WithTimeout configures timeout settings

type ResilienceConfig

type ResilienceConfig struct {
	CircuitBreaker *CircuitBreakerConfig
	RetryPolicy    *RetryPolicyConfig
	Timeout        *TimeoutConfig
	Fallback       *FallbackConfig
}

ResilienceConfig holds all resilience configurations

func DefaultResilienceConfig

func DefaultResilienceConfig() *ResilienceConfig

DefaultResilienceConfig returns a production-ready default configuration

type RetryPolicyConfig

type RetryPolicyConfig struct {
	Enabled           bool
	MaxAttempts       int           // Maximum number of execution attempts (initial + retries)
	MaxRetries        int           // Maximum number of retries (MaxAttempts - 1)
	MaxDuration       time.Duration // Maximum total duration for all attempts
	Delay             time.Duration // Fixed delay between retries
	BackoffInitial    time.Duration // Initial delay for exponential backoff
	BackoffMax        time.Duration // Maximum delay for exponential backoff
	RandomDelayMin    time.Duration // Minimum random delay
	RandomDelayMax    time.Duration // Maximum random delay
	JitterFactor      float64       // Jitter factor (0-1) to add randomness to delays
	Jitter            time.Duration // Time-based jitter to add to delays
	RetryableStatus   []int         // HTTP status codes that should trigger a retry
	AbortOnStatus     []int         // HTTP status codes that should abort retries immediately
	OnRetry           func(event failsafe.ExecutionEvent[*http.Response])
	OnRetriesExceeded func(event failsafe.ExecutionEvent[*http.Response])
	OnAbort           func(event failsafe.ExecutionEvent[*http.Response])
}

RetryPolicyConfig holds retry policy configuration

type ThresholdRatio

type ThresholdRatio struct {
	Failures uint // Number of failures
	Total    uint // Total executions
}

ThresholdRatio represents a ratio-based threshold (e.g., 3 failures out of 5 total)

type TimeoutConfig

type TimeoutConfig struct {
	Enabled           bool
	Duration          time.Duration // Maximum time allowed for execution
	OnTimeoutExceeded func(event failsafe.ExecutionDoneEvent[*http.Response])
}

TimeoutConfig holds timeout configuration

Jump to

Keyboard shortcuts

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