Documentation
¶
Overview ¶
Package httpclient provides a configurable HTTP adapter with built-in authentication, TLS, resilience (retry, circuit breaker, rate limiting), and streaming support.
The Adapter is both a full-capability HTTP client and a provider.RequestResponse implementation, so it can be used standalone or composed via the provider framework (WithResilience, Manager, Registry, etc.).
Basic Usage ¶
adapter, _ := httpclient.New(httpclient.Config{
Name: "my-api",
BaseURL: "https://api.example.com",
Timeout: 30 * time.Second,
Auth: httpclient.BearerAuth("my-token"),
})
resp, err := adapter.Do(ctx, httpclient.Request{
Method: http.MethodGet,
Path: "/users/123",
})
As a Provider ¶
// The adapter IS a provider — no wrapper needed. var p provider.RequestResponse[httpclient.Request, *httpclient.Response] = adapter resilient := provider.WithResilience(adapter, resilienceConfig)
REST Convenience ¶
user, err := httpclient.Get[User](adapter, ctx, "/users/123") created, err := httpclient.Post[User](adapter, ctx, "/users", body)
With Resilience ¶
adapter, _ := httpclient.New(httpclient.Config{
BaseURL: "https://api.example.com",
Retry: httpclient.DefaultRetryConfig(),
CircuitBreaker: httpclient.DefaultCircuitBreakerConfig("my-api"),
})
Index ¶
- func DefaultCircuitBreakerConfig(name string) *resilience.CircuitBreakerConfig
- func DefaultRateLimiterConfig(name string) *resilience.RateLimiterConfig
- func DefaultRetryConfig() *resilience.RetryConfig
- func IsAuth(err error) bool
- func IsConnection(err error) bool
- func IsNotFound(err error) bool
- func IsRateLimit(err error) bool
- func IsRetryable(err error) bool
- func IsServerError(err error) bool
- func IsTimeout(err error) bool
- type Adapter
- func (c *Adapter) Close(_ context.Context) error
- func (c *Adapter) Do(ctx context.Context, req Request) (*Response, error)
- func (c *Adapter) DoStream(ctx context.Context, req Request) (*StreamResponse, error)
- func (c *Adapter) Execute(ctx context.Context, req Request) (*Response, error)
- func (c *Adapter) GetConfig() Config
- func (c *Adapter) IsAvailable(_ context.Context) bool
- func (c *Adapter) Name() string
- func (c *Adapter) Unwrap() *http.Client
- type AuthConfig
- func APIKeyAuth(key string) *AuthConfig
- func APIKeyAuthHeader(key, headerName string) *AuthConfig
- func APIKeyAuthQuery(key, paramName string) *AuthConfig
- func BasicAuth(username, password string) *AuthConfig
- func BearerAuth(token string) *AuthConfig
- func CustomAuth(fn func(*http.Request)) *AuthConfig
- type AuthType
- type Component
- type Config
- type Error
- func ClassifyStatusCode(statusCode int, body []byte) *Error
- func NewAuthError(statusCode int, body []byte) *Error
- func NewConnectionError(err error) *Error
- func NewNotFoundError(body []byte) *Error
- func NewRateLimitError(body []byte) *Error
- func NewServerError(statusCode int, body []byte) *Error
- func NewTimeoutError(err error) *Error
- func NewValidationError(msg string) *Error
- type ErrorCode
- type FileField
- type MultipartBody
- type Option
- type Request
- type RequestOption
- type Response
- type StreamResponse
- type TypedResponse
- func Delete[T any](a *Adapter, ctx context.Context, path string, opts ...RequestOption) (*TypedResponse[T], error)
- func Get[T any](a *Adapter, ctx context.Context, path string, opts ...RequestOption) (*TypedResponse[T], error)
- func Patch[T any](a *Adapter, ctx context.Context, path string, body any, opts ...RequestOption) (*TypedResponse[T], error)
- func Post[T any](a *Adapter, ctx context.Context, path string, body any, opts ...RequestOption) (*TypedResponse[T], error)
- func Put[T any](a *Adapter, ctx context.Context, path string, body any, opts ...RequestOption) (*TypedResponse[T], error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig(name string) *resilience.CircuitBreakerConfig
DefaultCircuitBreakerConfig returns a default circuit breaker config.
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig(name string) *resilience.RateLimiterConfig
DefaultRateLimiterConfig returns a default rate limiter config.
func DefaultRetryConfig ¶
func DefaultRetryConfig() *resilience.RetryConfig
DefaultRetryConfig returns a default retry config suitable for HTTP clients.
func IsConnection ¶
IsConnection checks if an error is a connection error.
func IsNotFound ¶
IsNotFound checks if an error is a not-found error.
func IsRateLimit ¶
IsRateLimit checks if an error is a rate-limit error.
func IsServerError ¶
IsServerError checks if an error is a server error.
Types ¶
type Adapter ¶ added in v0.1.5
type Adapter struct {
// contains filtered or unexported fields
}
Adapter is a configurable HTTP adapter with built-in auth, TLS, and resilience. It can be used as a simple HTTP client or as a provider.RequestResponse for composition with the provider framework (WithResilience, Manager, Registry, etc.).
func (*Adapter) Close ¶ added in v0.1.5
Close releases resources held by the adapter (implements provider.Closeable).
func (*Adapter) DoStream ¶ added in v0.1.5
DoStream executes an HTTP request and returns a streaming response. The caller must close the returned StreamResponse when done. Note: Retry is not applied to streaming requests.
func (*Adapter) Execute ¶ added in v0.1.5
Execute sends an HTTP request and returns the response (implements provider.RequestResponse). This is equivalent to Do() but satisfies the provider interface for composition.
func (*Adapter) IsAvailable ¶ added in v0.1.5
IsAvailable checks if the adapter is ready to handle requests (implements provider.Provider).
type AuthConfig ¶
type AuthConfig struct {
// Type is the authentication method.
Type AuthType
// Token is the bearer token (AuthBearer).
Token string
// Username is the basic auth username (AuthBasic).
Username string
// Password is the basic auth password (AuthBasic).
Password string
// Key is the API key value (AuthAPIKey).
Key string
// In specifies where to place the API key: "header" (default) or "query" (AuthAPIKey).
In string
// Name is the header or query parameter name (AuthAPIKey). Defaults to "X-API-Key".
Name string
// Apply is a custom function to modify the request (AuthCustom).
Apply func(*http.Request)
}
AuthConfig configures request authentication.
func APIKeyAuth ¶
func APIKeyAuth(key string) *AuthConfig
APIKeyAuth creates an API key auth config sent via header.
func APIKeyAuthHeader ¶
func APIKeyAuthHeader(key, headerName string) *AuthConfig
APIKeyAuthHeader creates an API key auth config with a custom header name.
func APIKeyAuthQuery ¶
func APIKeyAuthQuery(key, paramName string) *AuthConfig
APIKeyAuthQuery creates an API key auth config sent via query parameter.
func BasicAuth ¶
func BasicAuth(username, password string) *AuthConfig
BasicAuth creates a basic auth config.
func BearerAuth ¶
func BearerAuth(token string) *AuthConfig
BearerAuth creates a bearer token auth config.
func CustomAuth ¶
func CustomAuth(fn func(*http.Request)) *AuthConfig
CustomAuth creates a custom auth config with a request modifier function.
type AuthType ¶
type AuthType int
AuthType identifies the authentication method.
const ( // AuthNone disables authentication. AuthNone AuthType = iota // AuthBearer uses Bearer token authentication. AuthBearer // AuthBasic uses HTTP Basic authentication. AuthBasic // AuthAPIKey uses API key authentication (header or query parameter). AuthAPIKey // AuthCustom uses a custom authentication function. AuthCustom )
type Component ¶ added in v0.1.5
type Component struct {
// contains filtered or unexported fields
}
Component wraps an Adapter with lifecycle management. Use this when the HTTP adapter is part of a managed application (e.g., with bootstrap.Start/Stop).
func NewComponent ¶ added in v0.1.5
NewComponent creates a new HTTP adapter component. The adapter is created lazily in Start().
func (*Component) Adapter ¶ added in v0.1.5
Adapter returns the underlying HTTP adapter. Must be called after Start().
func (*Component) Describe ¶ added in v0.1.5
func (c *Component) Describe() component.Description
Describe returns component description for the bootstrap summary.
type Config ¶
type Config struct {
// Name identifies this adapter instance (used by provider.Provider interface).
Name string `yaml:"name" mapstructure:"name"`
// BaseURL is the base URL prepended to all request paths.
BaseURL string `yaml:"base_url" mapstructure:"base_url"`
// Timeout is the default request timeout. Defaults to 30s.
Timeout time.Duration `yaml:"timeout" mapstructure:"timeout"`
// Auth configures default authentication applied to all requests.
// Individual requests can override this.
Auth *AuthConfig `yaml:"-" mapstructure:"-"`
// TLS configures TLS settings for the HTTP transport.
TLS *security.TLSConfig `yaml:"tls" mapstructure:"tls"`
// Headers are default headers applied to all requests.
Headers map[string]string `yaml:"headers" mapstructure:"headers"`
// Retry configures retry behavior. Nil disables retry.
Retry *resilience.RetryConfig `yaml:"-" mapstructure:"-"`
// CircuitBreaker configures circuit breaker behavior. Nil disables it.
CircuitBreaker *resilience.CircuitBreakerConfig `yaml:"-" mapstructure:"-"`
// RateLimiter configures rate limiting. Nil disables it.
RateLimiter *resilience.RateLimiterConfig `yaml:"-" mapstructure:"-"`
}
Config configures the HTTP adapter.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults fills in zero-value fields with sensible defaults.
type Error ¶
type Error struct {
// StatusCode is the HTTP status code (0 for connection-level errors).
StatusCode int
// Code classifies the error.
Code ErrorCode
// Message describes the error.
Message string
// Retryable indicates whether the operation can be retried.
Retryable bool
// Body is the original response body (may be nil).
Body []byte
// Err is the underlying error.
Err error
}
Error is a structured HTTP client error with classification.
func ClassifyStatusCode ¶
ClassifyStatusCode converts an HTTP status code into a typed error. Returns nil for 2xx status codes.
func NewAuthError ¶
NewAuthError creates an authentication error.
func NewConnectionError ¶
NewConnectionError creates a connection error.
func NewNotFoundError ¶
NewNotFoundError creates a not-found error.
func NewRateLimitError ¶
NewRateLimitError creates a rate-limit error.
func NewServerError ¶
NewServerError creates a server error.
func NewTimeoutError ¶
NewTimeoutError creates a timeout error.
func NewValidationError ¶
NewValidationError creates a validation error.
type ErrorCode ¶
type ErrorCode int
ErrorCode classifies HTTP client errors.
const ( // ErrCodeTimeout indicates a request or connection timeout. ErrCodeTimeout ErrorCode = iota // ErrCodeConnection indicates a connection failure (refused, DNS, etc). ErrCodeConnection // ErrCodeAuth indicates an authentication/authorization failure (401/403). ErrCodeAuth // ErrCodeNotFound indicates the resource was not found (404). ErrCodeNotFound // ErrCodeRateLimit indicates rate limiting (429). ErrCodeRateLimit // ErrCodeValidation indicates a client-side validation error (400). ErrCodeValidation // ErrCodeServer indicates a server-side error (5xx). ErrCodeServer )
type FileField ¶ added in v0.1.5
type FileField struct {
// FieldName is the form field name (e.g., "file", "audio").
FieldName string
// FileName is the file name sent to the server.
FileName string
// ContentType is the MIME type (e.g., "audio/wav"). If empty, uses application/octet-stream.
ContentType string
// Data is the file content. Used if Reader is nil.
Data []byte
// Reader is an alternative to Data for large files (streaming upload).
Reader io.Reader
}
FileField represents a file to upload in a multipart request.
type MultipartBody ¶ added in v0.1.5
type MultipartBody struct {
// Fields are simple key-value form fields.
Fields map[string]string
// Files are file upload fields.
Files []FileField
}
MultipartBody represents a multipart/form-data request body. Pass this as the Body field of a Request to automatically construct multipart encoding with the correct Content-Type header.
type Option ¶ added in v0.1.5
type Option func(*Adapter)
Option configures an Adapter during creation.
type Request ¶
type Request struct {
// Method is the HTTP method (GET, POST, PUT, PATCH, DELETE, etc).
Method string
// Path is appended to the client's BaseURL. Can be a full URL if BaseURL is empty.
Path string
// Headers are request-specific headers (merged with client defaults).
Headers map[string]string
// Query are URL query parameters.
Query map[string]string
// Body is the request body. Accepts io.Reader, []byte, string, or any value
// that will be JSON-encoded.
Body any
// Auth overrides the client-level auth for this request.
Auth *AuthConfig
}
Request describes an outbound HTTP request.
type RequestOption ¶ added in v0.1.5
type RequestOption func(*Request)
RequestOption configures a single request.
func WithHeader ¶ added in v0.1.5
func WithHeader(key, value string) RequestOption
WithHeader adds a header to the request.
func WithQueryParam ¶ added in v0.1.5
func WithQueryParam(key, value string) RequestOption
WithQueryParam adds a query parameter to the request.
func WithRequestAuth ¶ added in v0.1.5
func WithRequestAuth(auth *AuthConfig) RequestOption
WithRequestAuth overrides authentication for the request.
type Response ¶
type Response struct {
// StatusCode is the HTTP status code.
StatusCode int
// Headers are the response headers.
Headers map[string]string
// Body is the raw response body.
Body []byte
}
Response is the result of an HTTP request.
type StreamResponse ¶
type StreamResponse struct {
// StatusCode is the HTTP status code.
StatusCode int
// Headers are the response headers.
Headers map[string]string
// SSE is the Server-Sent Events reader (for text/event-stream responses).
SSE sse.Reader
// Body is the raw streaming body (for non-SSE streams).
Body io.ReadCloser
// contains filtered or unexported fields
}
StreamResponse wraps a streaming HTTP response.
func (*StreamResponse) Close ¶
func (r *StreamResponse) Close() error
Close releases all resources associated with the stream.
type TypedResponse ¶ added in v0.1.5
type TypedResponse[T any] struct { // StatusCode is the HTTP status code. StatusCode int // Headers are the response headers. Headers map[string]string // Data is the decoded response body. Data T }
TypedResponse wraps a response with a decoded body of type T.
func Delete ¶ added in v0.1.5
func Delete[T any](a *Adapter, ctx context.Context, path string, opts ...RequestOption) (*TypedResponse[T], error)
Delete performs a DELETE request and decodes the JSON response into type T.
func Get ¶ added in v0.1.5
func Get[T any](a *Adapter, ctx context.Context, path string, opts ...RequestOption) (*TypedResponse[T], error)
Get performs a GET request and decodes the JSON response into type T.
func Patch ¶ added in v0.1.5
func Patch[T any](a *Adapter, ctx context.Context, path string, body any, opts ...RequestOption) (*TypedResponse[T], error)
Patch performs a PATCH request with a JSON body and decodes the response into type T.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package rest provides a JSON-focused REST client built on the HTTP adapter.
|
Package rest provides a JSON-focused REST client built on the HTTP adapter. |
|
Package sse provides a reusable Server-Sent Events reader.
|
Package sse provides a reusable Server-Sent Events reader. |