httpclient

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

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

View Source
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

View Source
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 NewClient

func NewClient(config Config) *Client

NewClient creates a new HTTP client with proper User-Agent and authentication

func NewServiceClient

func NewServiceClient(baseURL, serviceName, authToken string) *Client

NewServiceClient creates a client configured for service-to-service communication

func (*Client) Delete

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

Delete performs a DELETE request

func (*Client) Do

func (c *Client) Do(ctx context.Context, req Request) (*Response, error)

Do performs an HTTP request with retry logic and circuit breaker

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

func (c *Client) GetBaseURL() string

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

func (c *Client) GetServiceName() string

GetServiceName returns the service name

func (*Client) HealthCheck

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

HealthCheck performs a health check against the target service

func (*Client) Post

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

Post performs a POST request

func (*Client) Put

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

Put performs a PUT request

func (*Client) UpdateAuthToken

func (c *Client) UpdateAuthToken(token string)

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

func (r *Response) DecodeJSON(v any) error

DecodeJSON decodes a JSON response into the provided interface

func (*Response) GetError

func (r *Response) GetError() error

GetError returns an error message from the response body if it's an error response

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if the response status code indicates success (2xx)

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.

Jump to

Keyboard shortcuts

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