httpclient

package
v1.3.30 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 16 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var ErrCircuitOpen = resilience.ErrOpen

ErrCircuitOpen is returned when the circuit breaker is open.

Functions

func IsStatus

func IsStatus(err error, code int) bool

IsStatus returns true if the error is an APIError with the given status code.

Types

type APIError

type APIError struct {
	StatusCode int
	Body       []byte
}

APIError is returned when the server responds with a 4xx or 5xx status.

func (*APIError) Error

func (e *APIError) Error() string

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.

func (APIKeyAuth) Apply

func (a APIKeyAuth) Apply(_ context.Context, req *http.Request) error

type AuthProvider

type AuthProvider interface {
	Apply(ctx context.Context, req *http.Request) error
}

AuthProvider applies authentication to an outgoing request.

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth sets HTTP Basic authentication.

func (BasicAuth) Apply

func (b BasicAuth) Apply(_ context.Context, req *http.Request) error

type BearerAuth

type BearerAuth struct{ Token string }

BearerAuth sets a static Bearer token on every request.

func (BearerAuth) Apply

func (b BearerAuth) Apply(_ context.Context, req *http.Request) error

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

func New(baseURL string, opts ...Option) *Client

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) Delete

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

Delete performs a DELETE request and decodes the response into out.

func (*Client) Get

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

Get performs a GET request and decodes the response body into out. Pass nil for out to discard the response body.

func (*Client) Patch

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

Patch performs a PATCH request, encoding body as JSON, and decodes the response into out.

func (*Client) Post

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

Post performs a POST request, encoding body as JSON, and decodes the response into out.

func (*Client) Put

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

Put performs a PUT 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.

func (*OAuth2ClientCredentials) Apply

type Option

type Option func(*Client)

Option configures a Client.

func WithAuth

func WithAuth(a AuthProvider) Option

WithAuth sets the authentication provider.

func WithCircuitBreaker

func WithCircuitBreaker(failureThreshold int, openTimeout time.Duration) Option

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

func WithHeader(key, value string) Option

WithHeader sets a default header sent on every request.

func WithLogger

func WithLogger(log *slog.Logger) Option

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

func WithRetry(attempts int, initialBackoff time.Duration) Option

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

func WithTimeout(d time.Duration) Option

WithTimeout sets a custom HTTP timeout (default: 30s).

type XMLBody

type XMLBody struct{ V any }

XMLBody wraps a value to signal it should be encoded as XML instead of JSON.

Jump to

Keyboard shortcuts

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