Documentation
¶
Overview ¶
Package httpclient provides a reusable HTTP client for calling external APIs. It handles authentication (Bearer, API key, Basic, OAuth2 client credentials), request/response encoding (JSON, XML), and consistent error handling.
The client is safe for concurrent use by any number of goroutines. A single Client instance should be shared across the application (not created per-request) so its connection pool is reused effectively.
Index ¶
- Variables
- func IsStatus(err error, code int) bool
- type APIError
- type APIKeyAuth
- type AuthProvider
- type BasicAuth
- type BearerAuth
- type Client
- func (c *Client) Delete(ctx context.Context, path string, out any) (*http.Response, error)
- func (c *Client) Get(ctx context.Context, path string, out any) (*http.Response, error)
- func (c *Client) Patch(ctx context.Context, path string, body, out any) (*http.Response, error)
- func (c *Client) Post(ctx context.Context, path string, body, out any) (*http.Response, error)
- func (c *Client) Put(ctx context.Context, path string, body, out any) (*http.Response, error)
- type OAuth2ClientCredentials
- type Option
- func WithAuth(a AuthProvider) Option
- func WithCircuitBreaker(failureThreshold int, openTimeout time.Duration) Option
- func WithHeader(key, value string) Option
- func WithLogger(log *slog.Logger) Option
- func WithMetrics(reg prometheus.Registerer) Option
- func WithRetry(attempts int, initialBackoff time.Duration) Option
- func WithTimeout(d time.Duration) Option
- type XMLBody
Constants ¶
This section is empty.
Variables ¶
var ErrCircuitOpen = resilience.ErrOpen
ErrCircuitOpen is returned when the circuit breaker is open.
Functions ¶
Types ¶
type APIKeyAuth ¶
type APIKeyAuth struct {
Key string
HeaderName string // e.g. "X-Api-Key"; if empty, uses query param
QueryParam string // e.g. "api_key"; used when HeaderName is empty
}
APIKeyAuth sets an API key in a header or query param.
type AuthProvider ¶
AuthProvider applies authentication to an outgoing request.
type BearerAuth ¶
type BearerAuth struct{ Token string }
BearerAuth sets a static Bearer token on every request.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a configured HTTP client for a single external API base URL. Create one instance per external API and reuse it across the application.
func New ¶
New constructs a Client for the given base URL.
A single Client instance is safe for concurrent use and should be shared across the application rather than created per-request. The underlying http.Transport maintains a connection pool; sharing the client allows connections to be reused, reducing latency and TCP connection churn.
func (*Client) Get ¶
Get performs a GET request and decodes the response body into out. Pass nil for out to discard the response body.
func (*Client) Patch ¶
Patch performs a PATCH request, encoding body as JSON, and decodes the response into out.
type OAuth2ClientCredentials ¶
type OAuth2ClientCredentials struct {
TokenURL string
ClientID string
ClientSecret string
Scopes []string
// contains filtered or unexported fields
}
OAuth2ClientCredentials fetches and caches tokens using the client_credentials grant. It automatically refreshes the token when it expires.
func NewOAuth2ClientCredentials ¶
func NewOAuth2ClientCredentials(tokenURL, clientID, clientSecret string, scopes []string, hc *http.Client) *OAuth2ClientCredentials
NewOAuth2ClientCredentials constructs an OAuth2 provider. An optional custom *http.Client can be passed (e.g. to set TLS or proxy); pass nil for default.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithCircuitBreaker ¶
WithCircuitBreaker attaches a circuit breaker to the client. When failureThreshold consecutive requests fail, the breaker opens and subsequent calls return ErrCircuitOpen immediately (without hitting the network) until openTimeout elapses and the breaker allows a trial request through.
This prevents goroutine pile-ups when an external API is down: instead of every goroutine waiting for the full HTTP timeout, they fail fast.
func WithHeader ¶
WithHeader sets a default header sent on every request.
func WithLogger ¶
WithLogger attaches a logger for request/response tracing.
func WithMetrics ¶
func WithMetrics(reg prometheus.Registerer) Option
WithMetrics registers Prometheus counters and histograms for outbound requests. Use the same registerer as the rest of the application (from observability.Telemetry) so metrics are served on the existing /metrics endpoint.
Recorded metrics:
httpclient_requests_total{host, method, status} – request count per outcome
httpclient_request_duration_seconds{host, method} – latency histogram
func WithRetry ¶
WithRetry enables automatic retry with exponential backoff for failed requests. Only use this for idempotent operations (GET, DELETE, PUT) or when you are sure the target API handles duplicate requests safely. attempts must be >= 1; initialBackoff is the first wait interval (doubled each retry).
func WithTimeout ¶
WithTimeout sets a custom HTTP timeout (default: 30s).