Help us shape the future of Go! Take the 2026 Go Developer Survey

httpclient

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package httpclient provides an HTTP client bundle for reliable service-to-service communication.

The HTTP client bundle provides:

  • HTTP client with circuit breaker protection
  • Retry logic with exponential backoff
  • Request/response logging and metrics
  • JWT authentication integration
  • Connection pooling and timeout management
  • Service discovery integration (future)
  • Request tracing and observability

Basic Usage

Add the HTTP client bundle to your application:

config := httpclient.Config{
	BaseURL: "https://api.example.com",
	Timeout: 30 * time.Second,
	RetryConfig: httpclient.RetryConfig{
		MaxRetries: 3,
		InitialInterval: 100 * time.Millisecond,
		MaxInterval: 5 * time.Second,
	},
}

bundle := httpclient.NewBundle(config)

app, err := framework.New(
	framework.WithConfig(&baseConfig),
	framework.WithBundle(bundle),
)

Making HTTP Calls

The bundle provides a high-level client interface:

client := bundle.Client()

// GET request with automatic retries and circuit breaker
var user User
err := client.Get(ctx, "/users/123", &user)

// POST request with request body
createReq := CreateUserRequest{Name: "John", Email: "john@example.com"}
var createResp CreateUserResponse
err := client.Post(ctx, "/users", createReq, &createResp)

Authentication Integration

The bundle automatically integrates with JWT authentication:

// JWT tokens are automatically injected into requests
err := client.Get(ctx, "/protected/resource", &response)

Circuit Breaker Protection

The bundle provides automatic circuit breaker protection:

// Circuit breaker automatically opens on failures
// and closes when service recovers
err := client.Get(ctx, "/unreliable-service", &response)
if errors.Is(err, httpclient.ErrCircuitBreakerOpen) {
	// Handle circuit breaker open state
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCircuitBreakerOpen = errors.New("circuit breaker is open")
	ErrMaxRetriesExceeded = errors.New("maximum retries exceeded")
	ErrHostNotAllowed     = errors.New("host not allowed")
)

Common errors

Functions

func WithJWTToken

func WithJWTToken(ctx context.Context, token string) context.Context

WithJWTToken adds a JWT token to the context for HTTP client authentication.

Types

type Bundle

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

Bundle provides HTTP client integration for Forge applications.

func NewBundle

func NewBundle(config Config) *Bundle

NewBundle creates a new HTTP client bundle.

func (*Bundle) Client

func (b *Bundle) Client() *Client

Client returns the enhanced HTTP client.

func (*Bundle) Close

func (b *Bundle) Close() error

Close is deprecated. Use Stop() instead for proper lifecycle integration. Maintained for backward compatibility.

func (*Bundle) EnableJWTIntegration

func (b *Bundle) EnableJWTIntegration(jwtBundle any) error

EnableJWTIntegration creates a client option that automatically injects JWT tokens.

func (*Bundle) Initialize

func (b *Bundle) Initialize(app *framework.App) error

Initialize sets up the HTTP client with all configured features.

func (*Bundle) Name

func (b *Bundle) Name() string

Name returns the bundle name.

func (*Bundle) Stop

func (b *Bundle) Stop(ctx context.Context) error

Stop implements the Bundle interface for graceful shutdown. Closes idle HTTP client connections respecting the context deadline.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Name        string                             // Circuit breaker name for metrics
	MaxRequests uint32                             // Max requests in half-open state (default: 3)
	Interval    time.Duration                      // Interval to clear failure counts (default: 60s)
	Timeout     time.Duration                      // Timeout in open state (default: 30s)
	ReadyToTrip func(counts gobreaker.Counts) bool // Custom trip function
}

CircuitBreakerConfig contains circuit breaker configuration.

type Client

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

Client provides enhanced HTTP client functionality with retries, circuit breaker, and observability.

func (*Client) CircuitBreakerCounts added in v0.3.0

func (c *Client) CircuitBreakerCounts() gobreaker.Counts

CircuitBreakerCounts returns the current circuit breaker counts.

func (*Client) CircuitBreakerState added in v0.3.0

func (c *Client) CircuitBreakerState() gobreaker.State

CircuitBreakerState returns the current circuit breaker state.

func (*Client) Delete

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

Delete performs a DELETE request.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, dest any) error

Get performs a GET request and unmarshals the response into dest.

func (*Client) HealthCheck

func (c *Client) HealthCheck(ctx context.Context, healthURL string) error

HealthCheck performs health checks for the HTTP client.

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body any, dest any) error

Post performs a POST request with the given body and unmarshals the response into dest.

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body any, dest any) error

Put performs a PUT request with the given body and unmarshals the response into dest.

func (*Client) RawRequest

func (c *Client) RawRequest(ctx context.Context, method, url string, headers map[string]string, body io.Reader) (*http.Response, error)

RawRequest performs a raw HTTP request with full control over request/response.

type Config

type Config struct {
	// BaseURL is the base URL for all requests (optional).
	BaseURL string

	// Timeout is the overall request timeout.
	Timeout time.Duration

	// Transport configuration
	MaxIdleConns          int           // Maximum idle connections (default: 100)
	MaxIdleConnsPerHost   int           // Maximum idle connections per host (default: 10)
	IdleConnTimeout       time.Duration // Idle connection timeout (default: 90 seconds)
	TLSHandshakeTimeout   time.Duration // TLS handshake timeout (default: 10 seconds)
	ExpectContinueTimeout time.Duration // Expect 100-continue timeout (default: 1 second)

	// TLS configuration
	TLSConfig *tls.Config

	// Authentication configuration
	EnableJWTAuth bool   // Enable automatic JWT authentication
	APIKeyHeader  string // Header name for API key (default: "X-API-Key")

	// Secure credential provider (replaces plain text APIKey)
	CredentialProvider CredentialProvider // Provider for secure credential access

	// AllowedHosts optionally restricts requests (including RawRequest and
	// resolved BaseURL+path lookups) to this set of hosts. This is opt-in
	// defense-in-depth against SSRF for services that pass user-influenced
	// URLs or paths through the client. Empty/nil (default) preserves the
	// existing unrestricted behavior.
	AllowedHosts []string

	// Retry configuration
	RetryConfig RetryConfig

	// Circuit breaker configuration
	CircuitBreakerConfig CircuitBreakerConfig

	// Logging and observability
	EnableRequestLogging bool // Enable request/response logging
	EnableMetrics        bool // Enable request metrics collection
	LogRequestBody       bool // Log request bodies (be careful with sensitive data)
	LogResponseBody      bool // Log response bodies (be careful with sensitive data)
	MaxLogBodySize       int  // Maximum body size to log (default: 1024 bytes)

	// User agent
	UserAgent string // User agent string (default: "Forge-HTTP-Client/1.0")
}

Config contains HTTP client configuration options.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the HTTP client configuration.

type CredentialProvider

type CredentialProvider interface {
	// GetAPIKey returns the API key for authentication.
	GetAPIKey(ctx context.Context) (string, error)

	// GetJWTToken returns a JWT token for authentication.
	GetJWTToken(ctx context.Context) (string, error)
}

CredentialProvider provides secure access to authentication credentials.

type HTTPError

type HTTPError struct {
	StatusCode int    `json:"status_code"`
	Status     string `json:"status"`
	Body       string `json:"body,omitempty"`
	URL        string `json:"url"`
	Method     string `json:"method"`
}

HTTPError represents an HTTP error response.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

func (*HTTPError) IsRetryableError

func (e *HTTPError) IsRetryableError() bool

IsRetryableError checks if an HTTP error should be retried.

type RetryConfig

type RetryConfig struct {
	MaxRetries          int           // Maximum number of retries (default: 3)
	InitialInterval     time.Duration // Initial retry interval (default: 100ms)
	MaxInterval         time.Duration // Maximum retry interval (default: 5s)
	Multiplier          float64       // Backoff multiplier (default: 2.0)
	RandomizationFactor float64       // Randomization factor (default: 0.1)
}

RetryConfig contains retry policy configuration.

type StaticCredentialProvider

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

StaticCredentialProvider provides static credentials (for development/testing only).

func NewStaticCredentialProvider

func NewStaticCredentialProvider(apiKey, jwtToken string) *StaticCredentialProvider

NewStaticCredentialProvider creates a credential provider with static values. WARNING: Only use for development/testing. In production, use secure credential stores.

func (*StaticCredentialProvider) GetAPIKey

func (p *StaticCredentialProvider) GetAPIKey(ctx context.Context) (string, error)

GetAPIKey returns the static API key.

func (*StaticCredentialProvider) GetJWTToken

func (p *StaticCredentialProvider) GetJWTToken(ctx context.Context) (string, error)

GetJWTToken returns the static JWT token.

Jump to

Keyboard shortcuts

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