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 ¶
- Variables
- func WithJWTToken(ctx context.Context, token string) context.Context
- type Bundle
- type CircuitBreakerConfig
- type Client
- func (c *Client) Delete(ctx context.Context, path string) error
- func (c *Client) Get(ctx context.Context, path string, dest interface{}) error
- func (c *Client) GetCircuitBreakerCounts() gobreaker.Counts
- func (c *Client) GetCircuitBreakerState() gobreaker.State
- func (c *Client) HealthCheck(ctx context.Context, healthURL string) error
- func (c *Client) Post(ctx context.Context, path string, body interface{}, dest interface{}) error
- func (c *Client) Put(ctx context.Context, path string, body interface{}, dest interface{}) error
- func (c *Client) RawRequest(ctx context.Context, method, url string, headers map[string]string, ...) (*http.Response, error)
- type Config
- type CredentialProvider
- type HTTPError
- type RetryConfig
- type StaticCredentialProvider
Constants ¶
This section is empty.
Variables ¶
var ( ErrCircuitBreakerOpen = fmt.Errorf("circuit breaker is open") ErrMaxRetriesExceeded = fmt.Errorf("maximum retries exceeded") )
Common errors
Functions ¶
Types ¶
type Bundle ¶
type Bundle struct {
// contains filtered or unexported fields
}
Bundle provides HTTP client integration for Forge applications.
func (*Bundle) Close ¶
Close is deprecated. Use Stop() instead for proper lifecycle integration. Maintained for backward compatibility.
func (*Bundle) EnableJWTIntegration ¶
EnableJWTIntegration creates a client option that automatically injects JWT tokens.
func (*Bundle) Initialize ¶
Initialize sets up the HTTP client with all configured features.
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) GetCircuitBreakerCounts ¶
GetCircuitBreakerCounts returns the current circuit breaker counts.
func (*Client) GetCircuitBreakerState ¶
GetCircuitBreakerState returns the current circuit breaker state.
func (*Client) HealthCheck ¶
HealthCheck performs health checks for the HTTP client.
func (*Client) Post ¶
Post performs a POST request with the given body and unmarshals the response into dest.
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
// 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.
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) IsRetryableError ¶
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.