Documentation
¶
Overview ¶
Package httpclient is an HTTP client for calling other services.
Over net/http it adds the things a service-to-service call needs and a bare client leaves to you: retries with backoff, a circuit breaker that stops hammering a peer that is already down, distributed-trace propagation, and Prometheus metrics per target service.
Index ¶
- Constants
- func ContextWithTrace(ctx context.Context, trace *TraceContext) context.Context
- type CircuitBreaker
- type CircuitBreakerState
- type Client
- func (c *Client) Delete(ctx context.Context, path string) (*Response, error)
- func (c *Client) Do(ctx context.Context, req Request) (*Response, error)
- func (c *Client) Get(ctx context.Context, path string, queryParams map[string]string) (*Response, error)
- func (c *Client) GetBaseURL() string
- func (c *Client) GetCircuitBreakerState() CircuitBreakerState
- func (c *Client) GetServiceName() string
- func (c *Client) HealthCheck(ctx context.Context) error
- func (c *Client) Post(ctx context.Context, path string, body any) (*Response, error)
- func (c *Client) Put(ctx context.Context, path string, body any) (*Response, error)
- func (c *Client) UpdateAuthToken(token string)
- type Config
- type HTTPClientMetrics
- type Request
- type Response
- type RetryConfig
- type TraceContext
Constants ¶
const ( // Standard distributed tracing headers TraceIDHeader = "X-Trace-ID" SpanIDHeader = "X-Span-ID" ParentSpanIDHeader = "X-Parent-Span-ID" RequestIDHeader = "X-Request-ID" // TraceparentHeader carries the same trace in the W3C Trace Context // format, so OpenTelemetry-instrumented peers can join the trace without // this package adopting an OTel dependency. TraceparentHeader = "traceparent" // Custom correlation headers CorrelationIDHeader = "X-Correlation-ID" UserIDHeader = "X-User-ID" ServiceChainHeader = "X-Service-Chain" )
Distributed tracing support
const DefaultAPIKeyPrefix = "sk_"
Client represents a configured HTTP client for service-to-service communication DefaultAPIKeyPrefix is the service-API-key prefix assumed when Config leaves APIKeyPrefix empty.
Variables ¶
This section is empty.
Functions ¶
func ContextWithTrace ¶
func ContextWithTrace(ctx context.Context, trace *TraceContext) context.Context
ContextWithTrace adds trace context to Go context
Types ¶
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements a simple circuit breaker pattern
func NewCircuitBreaker ¶
func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
func (*CircuitBreaker) CanExecute ¶
func (cb *CircuitBreaker) CanExecute() bool
CanExecute checks if the circuit breaker allows execution
func (*CircuitBreaker) RecordFailure ¶
func (cb *CircuitBreaker) RecordFailure()
RecordFailure records a failed execution
func (*CircuitBreaker) RecordSuccess ¶
func (cb *CircuitBreaker) RecordSuccess()
RecordSuccess records a successful execution
type CircuitBreakerState ¶
type CircuitBreakerState int
CircuitBreakerState represents the state of the circuit breaker
const ( CircuitClosed CircuitBreakerState = iota CircuitOpen CircuitHalfOpen )
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func NewServiceClient ¶
NewServiceClient creates a client configured for service-to-service communication
func (*Client) Get ¶
func (c *Client) Get(ctx context.Context, path string, queryParams map[string]string) (*Response, error)
Get performs a GET request
func (*Client) GetBaseURL ¶
GetBaseURL returns the base URL of the client
func (*Client) GetCircuitBreakerState ¶
func (c *Client) GetCircuitBreakerState() CircuitBreakerState
GetCircuitBreakerState returns the current circuit breaker state
func (*Client) GetServiceName ¶
GetServiceName returns the service name
func (*Client) HealthCheck ¶
HealthCheck performs a health check against the target service
func (*Client) UpdateAuthToken ¶
UpdateAuthToken updates the authentication token
type Config ¶
type Config struct {
BaseURL string
ServiceName string
// TargetServiceName labels metrics for the called service. When empty it
// is derived from the BaseURL hostname.
TargetServiceName string
AuthToken string
// APIKeyPrefix identifies an AuthToken that is a service API key rather
// than a user session token: a token carrying this prefix is sent as
// X-API-Key, anything else as an Authorization bearer token. Defaults to
// DefaultAPIKeyPrefix.
APIKeyPrefix string
Timeout time.Duration
Headers map[string]string
RetryConfig *RetryConfig
CircuitBreaker *CircuitBreaker
}
Config holds configuration for the HTTP client
type HTTPClientMetrics ¶
type HTTPClientMetrics struct {
// contains filtered or unexported fields
}
HTTPClientMetrics handles metrics collection for HTTP requests
func NewHTTPClientMetrics ¶
func NewHTTPClientMetrics(serviceName, targetService string) *HTTPClientMetrics
NewHTTPClientMetrics creates a new metrics collector
func (*HTTPClientMetrics) RecordCircuitBreakerState ¶
func (m *HTTPClientMetrics) RecordCircuitBreakerState(state CircuitBreakerState)
RecordCircuitBreakerState records circuit breaker state changes
func (*HTTPClientMetrics) RecordError ¶
func (m *HTTPClientMetrics) RecordError(errorType string)
RecordError records HTTP client errors
func (*HTTPClientMetrics) RecordRequest ¶
func (m *HTTPClientMetrics) RecordRequest(method string, statusCode int, duration time.Duration)
RecordRequest records HTTP request metrics
func (*HTTPClientMetrics) RecordRetryAttempt ¶
func (m *HTTPClientMetrics) RecordRetryAttempt(reason string)
RecordRetryAttempt records retry attempts
type Request ¶
type Request struct {
Method string
Path string
Body any
Headers map[string]string
QueryParams map[string]string
}
Request represents an HTTP request configuration
type Response ¶
type Response struct {
StatusCode int
Body []byte
Headers http.Header
TraceContext *TraceContext
}
Response represents an HTTP response
func (*Response) DecodeJSON ¶
DecodeJSON decodes a JSON response into the provided interface
type RetryConfig ¶
type RetryConfig struct {
MaxRetries int
InitialWait time.Duration
MaxWait time.Duration
Multiplier float64
}
RetryConfig defines retry behavior
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns a sensible default retry configuration
type TraceContext ¶
type TraceContext struct {
TraceID string
SpanID string
ParentSpanID string
RequestID string
CorrelationID string
UserID string
ServiceChain []string
}
TraceContext holds distributed tracing information
func NewTraceContext ¶
func NewTraceContext(ctx context.Context) *TraceContext
NewTraceContext creates a new trace context or continues existing one
func TraceContextFromHeaders ¶
func TraceContextFromHeaders(headers http.Header) *TraceContext
FromHeaders creates trace context from HTTP headers
func TraceFromContext ¶
func TraceFromContext(ctx context.Context) *TraceContext
TraceFromContext extracts trace context from Go context
func (*TraceContext) AddToServiceChain ¶
func (tc *TraceContext) AddToServiceChain(serviceName string)
AddToServiceChain adds a service to the service call chain
func (*TraceContext) ToHeaders ¶
func (tc *TraceContext) ToHeaders() map[string]string
ToHeaders converts trace context to HTTP headers
func (*TraceContext) Traceparent ¶
func (tc *TraceContext) Traceparent() string
Traceparent renders the trace in the W3C Trace Context format, or returns the empty string when the identifiers do not fit that format — a trace-id must be 32 hex digits and a span-id 16, and neither may be all zeroes.