Documentation
¶
Overview ¶
Package httpc provides a fluent, batteries-included HTTP client wrapper that makes common patterns trivial while staying close to Go's standard library philosophy.
Index ¶
- Variables
- type AdaptiveRateLimiter
- type BearerTokenFunc
- type CircuitBreakerConfig
- type CircuitBreakerOption
- func WithCircuitBreakerInterval(d time.Duration) CircuitBreakerOption
- func WithCircuitBreakerMaxRequests(n int) CircuitBreakerOption
- func WithCircuitBreakerName(name string) CircuitBreakerOption
- func WithCircuitBreakerStateChange(fn func(name string, from, to gobreaker.State)) CircuitBreakerOption
- func WithCircuitBreakerTimeout(d time.Duration) CircuitBreakerOption
- func WithMaxFailures(n int) CircuitBreakerOption
- type CircuitState
- type Client
- func (c *Client) Delete(url string) *Request
- func (c *Client) Do(req *http.Request) (*Response, error)
- func (c *Client) Get(url string) *Request
- func (c *Client) Head(url string) *Request
- func (c *Client) Options(url string) *Request
- func (c *Client) Patch(url string) *Request
- func (c *Client) Post(url string) *Request
- func (c *Client) Put(url string) *Request
- func (c *Client) Request(method, url string) *Request
- func (c *Client) WithBaseURL(url string) *Client
- func (c *Client) WithCircuitBreaker(maxFailures int, timeout time.Duration) *Client
- func (c *Client) WithCircuitBreakerConfig(config *CircuitBreakerConfig) *Client
- func (c *Client) WithHTTPClient(client *http.Client) *Client
- func (c *Client) WithHeader(key, value string) *Client
- func (c *Client) WithHeaders(headers map[string]string) *Client
- func (c *Client) WithLogger(logger Logger) *Client
- func (c *Client) WithMiddleware(mw Middleware) *Client
- func (c *Client) WithRateLimiter(requestsPerSecond float64) *Client
- func (c *Client) WithRateLimiterConfig(requestsPerSecond float64, burst int) *Client
- func (c *Client) WithRetry(maxAttempts int, initialDelay time.Duration) *Client
- func (c *Client) WithRetryConfig(config *RetryConfig) *Client
- func (c *Client) WithTimeout(timeout time.Duration) *Client
- type DefaultLogger
- func (l *DefaultLogger) LogError(req *http.Request, err error, duration time.Duration)
- func (l *DefaultLogger) LogRequest(req *http.Request)
- func (l *DefaultLogger) LogResponse(req *http.Request, resp *http.Response, duration time.Duration)
- func (l *DefaultLogger) LogRetry(req *http.Request, attempt int, delay time.Duration)
- type Error
- type ErrorHandler
- type HTTPHandler
- type Handler
- type Logger
- type Middleware
- func AuthMiddleware(scheme, credentials string) Middleware
- func BearerTokenMiddleware(token string) Middleware
- func Chain(middlewares ...Middleware) Middleware
- func DynamicBearerTokenMiddleware(tokenFunc BearerTokenFunc) Middleware
- func ErrorHandlerMiddleware(handler ErrorHandler) Middleware
- func HeadersMiddleware(headers map[string]string) Middleware
- func LoggingMiddleware(logger Logger) Middleware
- func RateLimiterMiddleware(limiter *rate.Limiter) Middleware
- func RequestIDMiddleware(headerName string, idFunc func() string) Middleware
- func ResponseHookMiddleware(hook ResponseHook) Middleware
- func UserAgentMiddleware(userAgent string) Middleware
- type NopLogger
- func (l NopLogger) LogError(req *http.Request, err error, duration time.Duration)
- func (l NopLogger) LogRequest(req *http.Request)
- func (l NopLogger) LogResponse(req *http.Request, resp *http.Response, duration time.Duration)
- func (l NopLogger) LogRetry(req *http.Request, attempt int, delay time.Duration)
- type RateLimiterConfig
- type RateLimiterOption
- type Request
- func (r *Request) BasicAuth(username, password string) *Request
- func (r *Request) Bearer(token string) *Request
- func (r *Request) Body(body io.Reader) *Request
- func (r *Request) BodyBytes(body []byte) *Request
- func (r *Request) BodyString(body string) *Request
- func (r *Request) Bytes() ([]byte, error)
- func (r *Request) Context(ctx context.Context) *Request
- func (r *Request) DecodeJSON(v interface{}) error
- func (r *Request) DecodeJSONResponse(v interface{}) (*Response, error)
- func (r *Request) Do() (*Response, error)
- func (r *Request) ExpectStatus(codes ...int) *Request
- func (r *Request) Form(data map[string]string) *Request
- func (r *Request) FormValues(data url.Values) *Request
- func (r *Request) Header(key, value string) *Request
- func (r *Request) Headers(headers map[string]string) *Request
- func (r *Request) JSON(v interface{}) *Request
- func (r *Request) Query(key, value string) *Request
- func (r *Request) QueryParams(params map[string]string) *Request
- func (r *Request) QueryValues(params url.Values) *Request
- func (r *Request) String() (string, error)
- func (r *Request) Timeout(timeout time.Duration) *Request
- type Response
- func (r *Response) Body() io.ReadCloser
- func (r *Response) Bytes() ([]byte, error)
- func (r *Response) Close() error
- func (r *Response) ContentLength() int64
- func (r *Response) ContentType() string
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Header(key string) string
- func (r *Response) Headers() http.Header
- func (r *Response) IsClientError() bool
- func (r *Response) IsError() bool
- func (r *Response) IsServerError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) JSON(v interface{}) error
- func (r *Response) Location() (string, error)
- func (r *Response) Raw() *http.Response
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() (string, error)
- type ResponseHook
- type RetryConfig
- type RetryOption
Constants ¶
This section is empty.
Variables ¶
var ( // ErrServerError indicates a 5xx server error response. ErrServerError = errors.New("server error") // ErrClientError indicates a 4xx client error response. ErrClientError = errors.New("client error") // ErrTimeout indicates a request timeout. ErrTimeout = errors.New("request timeout") // ErrCircuitOpen indicates the circuit breaker is open. ErrCircuitOpen = errors.New("circuit breaker is open") // ErrRateLimited indicates rate limit exceeded. ErrRateLimited = errors.New("rate limit exceeded") // ErrRetryExhausted indicates all retry attempts failed. ErrRetryExhausted = errors.New("retry attempts exhausted") )
Common errors that can be checked with errors.Is().
Functions ¶
This section is empty.
Types ¶
type AdaptiveRateLimiter ¶
type AdaptiveRateLimiter struct {
// contains filtered or unexported fields
}
AdaptiveRateLimiter adjusts the rate limit based on server responses.
func NewAdaptiveRateLimiter ¶
func NewAdaptiveRateLimiter(minRate, maxRate float64) *AdaptiveRateLimiter
NewAdaptiveRateLimiter creates a new adaptive rate limiter.
func (*AdaptiveRateLimiter) CurrentRate ¶
func (a *AdaptiveRateLimiter) CurrentRate() float64
CurrentRate returns the current rate limit.
func (*AdaptiveRateLimiter) RecordFailure ¶
func (a *AdaptiveRateLimiter) RecordFailure()
RecordFailure records a failed request (e.g., 429) and reduces the rate.
func (*AdaptiveRateLimiter) RecordSuccess ¶
func (a *AdaptiveRateLimiter) RecordSuccess()
RecordSuccess records a successful request and potentially increases the rate.
type BearerTokenFunc ¶
BearerTokenFunc is a function that returns a bearer token. This is useful for tokens that expire and need to be refreshed.
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// Name is the name of the circuit breaker (for logging/metrics).
Name string
// MaxFailures is the number of consecutive failures before opening the circuit.
// Default: 5
MaxFailures int
// MaxRequests is the maximum number of requests allowed in half-open state.
// Default: 1
MaxRequests int
// Interval is the cyclical period of the closed state.
// If 0, the circuit breaker doesn't clear counts in closed state.
Interval time.Duration
// Timeout is the duration to wait before transitioning from open to half-open.
// Default: 60 seconds
Timeout time.Duration
// OnStateChange is called when the circuit breaker state changes.
OnStateChange func(name string, from, to gobreaker.State)
}
CircuitBreakerConfig configures the circuit breaker behavior.
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig() *CircuitBreakerConfig
DefaultCircuitBreakerConfig returns the default circuit breaker configuration.
func NewCircuitBreakerConfig ¶
func NewCircuitBreakerConfig(opts ...CircuitBreakerOption) *CircuitBreakerConfig
NewCircuitBreakerConfig creates a new CircuitBreakerConfig with the given options.
type CircuitBreakerOption ¶
type CircuitBreakerOption func(*CircuitBreakerConfig)
CircuitBreakerOption is a function that modifies CircuitBreakerConfig.
func WithCircuitBreakerInterval ¶
func WithCircuitBreakerInterval(d time.Duration) CircuitBreakerOption
WithCircuitBreakerInterval sets the cyclical period of the closed state.
func WithCircuitBreakerMaxRequests ¶
func WithCircuitBreakerMaxRequests(n int) CircuitBreakerOption
WithMaxRequests sets the maximum number of requests in half-open state.
func WithCircuitBreakerName ¶
func WithCircuitBreakerName(name string) CircuitBreakerOption
WithCircuitBreakerName sets the name of the circuit breaker.
func WithCircuitBreakerStateChange ¶
func WithCircuitBreakerStateChange(fn func(name string, from, to gobreaker.State)) CircuitBreakerOption
WithCircuitBreakerStateChange sets a callback for state changes.
func WithCircuitBreakerTimeout ¶
func WithCircuitBreakerTimeout(d time.Duration) CircuitBreakerOption
WithCircuitBreakerTimeout sets the duration before transitioning from open to half-open.
func WithMaxFailures ¶
func WithMaxFailures(n int) CircuitBreakerOption
WithMaxFailures sets the maximum number of failures before opening the circuit.
type CircuitState ¶
type CircuitState int
CircuitState represents the state of the circuit breaker.
const ( // CircuitClosed allows requests to pass through. CircuitClosed CircuitState = iota // CircuitHalfOpen allows a limited number of requests to test the service. CircuitHalfOpen // CircuitOpen blocks all requests. CircuitOpen )
func (CircuitState) String ¶
func (s CircuitState) String() string
String returns the string representation of the circuit state.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main HTTP client with fluent configuration. Use New() to create a new client with sensible defaults.
func New ¶
func New() *Client
New creates a new HTTP client with sensible defaults.
Example:
client := httpc.New()
resp, err := client.Get("https://api.example.com/users").Do()
func (*Client) Do ¶
Do executes a pre-built http.Request with all client configurations. This is useful when you need to work with existing http.Request objects.
func (*Client) Get ¶
Get creates a new GET request.
Example:
resp, err := client.Get("https://api.example.com/users").Do()
func (*Client) Post ¶
Post creates a new POST request.
Example:
resp, err := client.Post("https://api.example.com/users").JSON(user).Do()
func (*Client) WithBaseURL ¶
WithBaseURL sets the base URL for all requests. The path in request methods will be appended to this URL.
Example:
client := httpc.New().WithBaseURL("https://api.example.com")
resp, err := client.Get("/users").Do() // GET https://api.example.com/users
func (*Client) WithCircuitBreaker ¶
WithCircuitBreaker configures a circuit breaker pattern.
Parameters:
- maxFailures: Number of failures before opening the circuit
- timeout: Duration to wait before attempting to close the circuit
Example:
client := httpc.New().WithCircuitBreaker(5, time.Minute)
func (*Client) WithCircuitBreakerConfig ¶
func (c *Client) WithCircuitBreakerConfig(config *CircuitBreakerConfig) *Client
WithCircuitBreakerConfig configures a circuit breaker with custom settings.
func (*Client) WithHTTPClient ¶
WithHTTPClient sets a custom http.Client. Use this if you need custom transport settings like TLS configuration.
func (*Client) WithHeader ¶
WithHeader sets a default header that will be included in all requests.
Example:
client := httpc.New().WithHeader("User-Agent", "MyApp/1.0")
func (*Client) WithHeaders ¶
WithHeaders sets multiple default headers at once.
func (*Client) WithLogger ¶
WithLogger sets a custom logger for the client.
func (*Client) WithMiddleware ¶
func (c *Client) WithMiddleware(mw Middleware) *Client
WithMiddleware adds a middleware function to the client. Middlewares are executed in the order they are added.
func (*Client) WithRateLimiter ¶
WithRateLimiter configures rate limiting.
Parameters:
- requestsPerSecond: Maximum number of requests per second
Example:
client := httpc.New().WithRateLimiter(10) // 10 requests per second
func (*Client) WithRateLimiterConfig ¶
WithRateLimiterConfig configures rate limiting with burst capacity.
Parameters:
- requestsPerSecond: Maximum sustained rate of requests per second
- burst: Maximum burst size (tokens available at any moment)
func (*Client) WithRetry ¶
WithRetry configures automatic retry with exponential backoff.
Parameters:
- maxAttempts: Maximum number of attempts (including the initial request)
- initialDelay: Initial delay between retries (will be exponentially increased)
Example:
client := httpc.New().WithRetry(3, time.Second)
func (*Client) WithRetryConfig ¶
func (c *Client) WithRetryConfig(config *RetryConfig) *Client
WithRetryConfig configures automatic retry with custom settings.
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger implements Logger using slog.
func NewDefaultLogger ¶
func NewDefaultLogger(level slog.Level) *DefaultLogger
NewDefaultLogger creates a new DefaultLogger with the specified level.
func NewDefaultLoggerWithHandler ¶
func NewDefaultLoggerWithHandler(handler slog.Handler) *DefaultLogger
NewDefaultLoggerWithHandler creates a new DefaultLogger with a custom slog handler.
func (*DefaultLogger) LogRequest ¶
func (l *DefaultLogger) LogRequest(req *http.Request)
LogRequest logs an outgoing request.
func (*DefaultLogger) LogResponse ¶
LogResponse logs a received response.
type Error ¶
type Error struct {
// Op is the operation that failed (e.g., "do", "retry", "circuit_breaker")
Op string
// URL is the URL of the request that failed
URL string
// StatusCode is the HTTP status code (if available)
StatusCode int
// Err is the underlying error
Err error
}
Error represents an HTTP client error with additional context.
func (*Error) IsClientError ¶
IsClientError returns true if this is a 4xx client error.
func (*Error) IsRetryable ¶
IsRetryable returns true if the error is potentially retryable.
func (*Error) IsServerError ¶
IsServerError returns true if this is a 5xx server error.
type ErrorHandler ¶
ErrorHandler is a function that inspects a response and returns an error if appropriate.
type HTTPHandler ¶
HTTPHandler is a function that processes an http.Request and returns a Response.
type Handler ¶
type Handler = HTTPHandler
Handler is an alias for HTTPHandler for backward compatibility. Deprecated: Use HTTPHandler instead.
type Logger ¶
type Logger interface {
// LogRequest logs an outgoing request.
LogRequest(req *http.Request)
// LogResponse logs a received response.
LogResponse(req *http.Request, resp *http.Response, duration time.Duration)
// LogError logs a request error.
LogError(req *http.Request, err error, duration time.Duration)
// LogRetry logs a retry attempt.
LogRetry(req *http.Request, attempt int, delay time.Duration)
}
Logger defines the interface for httpc logging.
type Middleware ¶
type Middleware func(req *http.Request, next HTTPHandler) (*Response, error)
Middleware is a function that wraps an HTTPHandler. Middlewares can inspect or modify requests and responses.
Example:
authMiddleware := func(req *http.Request, next httpc.HTTPHandler) (*httpc.Response, error) {
req.Header.Set("Authorization", "Bearer " + getToken())
return next(req)
}
client := httpc.New().WithMiddleware(authMiddleware)
func AuthMiddleware ¶
func AuthMiddleware(scheme, credentials string) Middleware
AuthMiddleware creates a middleware that adds an Authorization header.
func BearerTokenMiddleware ¶
func BearerTokenMiddleware(token string) Middleware
BearerTokenMiddleware creates a middleware that adds a Bearer token.
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain combines multiple middlewares into a single middleware. Middlewares are executed in the order provided.
func DynamicBearerTokenMiddleware ¶
func DynamicBearerTokenMiddleware(tokenFunc BearerTokenFunc) Middleware
DynamicBearerTokenMiddleware creates a middleware that fetches a Bearer token dynamically. This is useful for tokens that expire and need to be refreshed.
func ErrorHandlerMiddleware ¶
func ErrorHandlerMiddleware(handler ErrorHandler) Middleware
ErrorHandlerMiddleware creates a middleware that converts specific status codes to errors.
func HeadersMiddleware ¶
func HeadersMiddleware(headers map[string]string) Middleware
HeadersMiddleware creates a middleware that adds default headers.
func LoggingMiddleware ¶
func LoggingMiddleware(logger Logger) Middleware
LoggingMiddleware creates a middleware that logs requests and responses. This can be used as an alternative to the client-level logger.
func RateLimiterMiddleware ¶
func RateLimiterMiddleware(limiter *rate.Limiter) Middleware
RateLimiterMiddleware creates a middleware that applies rate limiting. This can be used as an alternative to the client-level rate limiter.
func RequestIDMiddleware ¶
func RequestIDMiddleware(headerName string, idFunc func() string) Middleware
RequestIDMiddleware creates a middleware that adds a request ID header. The idFunc generates a new ID for each request.
func ResponseHookMiddleware ¶
func ResponseHookMiddleware(hook ResponseHook) Middleware
ResponseHookMiddleware creates a middleware that calls a hook for every response.
func UserAgentMiddleware ¶
func UserAgentMiddleware(userAgent string) Middleware
UserAgentMiddleware creates a middleware that sets the User-Agent header.
type NopLogger ¶
type NopLogger struct{}
NopLogger is a logger that does nothing.
func (NopLogger) LogRequest ¶
LogRequest does nothing.
func (NopLogger) LogResponse ¶
LogResponse does nothing.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
// RequestsPerSecond is the maximum sustained rate of requests per second.
RequestsPerSecond float64
// Burst is the maximum burst size (tokens available at any moment).
// If 0, defaults to RequestsPerSecond.
Burst int
}
RateLimiterConfig configures the rate limiter behavior.
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig() *RateLimiterConfig
DefaultRateLimiterConfig returns the default rate limiter configuration.
func NewRateLimiterConfig ¶
func NewRateLimiterConfig(opts ...RateLimiterOption) *RateLimiterConfig
NewRateLimiterConfig creates a new RateLimiterConfig with the given options.
func (*RateLimiterConfig) NewRateLimiter ¶
func (c *RateLimiterConfig) NewRateLimiter() *rate.Limiter
NewRateLimiter creates a new rate.Limiter from the configuration.
type RateLimiterOption ¶
type RateLimiterOption func(*RateLimiterConfig)
RateLimiterOption is a function that modifies RateLimiterConfig.
func WithRequestsPerSecond ¶
func WithRequestsPerSecond(rps float64) RateLimiterOption
WithRequestsPerSecond sets the maximum requests per second.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request represents an HTTP request being built. Use the fluent methods to configure the request, then call Do() or DecodeJSON() to execute.
func (*Request) Bearer ¶
Bearer sets the Authorization header with a Bearer token.
Example:
resp, err := client.Get("/users").Bearer("your-token").Do()
func (*Request) BodyString ¶
BodyString sets the request body from a string.
func (*Request) DecodeJSON ¶
DecodeJSON executes the request and decodes the JSON response into v. This is a convenience method that combines Do() and Response.JSON().
Example:
var users []User
err := client.Get("/users").DecodeJSON(&users)
func (*Request) DecodeJSONResponse ¶
DecodeJSONResponse executes the request and decodes the JSON response into v, also returning the Response for further inspection.
func (*Request) Do ¶
Do executes the request and returns the response.
Example:
resp, err := client.Get("/users").Do()
if err != nil {
log.Fatal(err)
}
defer resp.Close()
func (*Request) ExpectStatus ¶
ExpectStatus specifies expected status codes. If the response status doesn't match any of these, Do() will return an error.
Example:
resp, err := client.Post("/users").JSON(user).ExpectStatus(201).Do()
func (*Request) Form ¶
Form sets the request body as form-urlencoded data.
Example:
resp, err := client.Post("/login").Form(map[string]string{"user": "john", "pass": "secret"}).Do()
func (*Request) FormValues ¶
FormValues sets the request body from url.Values.
func (*Request) Header ¶
Header sets a header for this request.
Example:
resp, err := client.Get("/users").Header("Authorization", "Bearer token").Do()
func (*Request) JSON ¶
JSON sets the request body as JSON and sets the Content-Type header.
Example:
user := User{Name: "John", Email: "john@example.com"}
resp, err := client.Post("/users").JSON(user).Do()
func (*Request) Query ¶
Query adds a query parameter to the request URL.
Example:
resp, err := client.Get("/users").Query("page", "1").Query("limit", "10").Do()
func (*Request) QueryParams ¶
QueryParams adds multiple query parameters at once.
func (*Request) QueryValues ¶
QueryValues adds url.Values as query parameters.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response wraps an http.Response with convenient helper methods.
func (*Response) Body ¶
func (r *Response) Body() io.ReadCloser
Body returns the response body as an io.ReadCloser. Remember to close it when done.
func (*Response) Bytes ¶
Bytes reads and returns the entire response body as bytes. The body is cached, so subsequent calls return the same data.
func (*Response) ContentLength ¶
ContentLength returns the Content-Length header value.
func (*Response) ContentType ¶
ContentType returns the Content-Type header value.
func (*Response) IsClientError ¶
IsClientError returns true if the status code is in the 4xx range.
func (*Response) IsServerError ¶
IsServerError returns true if the status code is in the 5xx range.
func (*Response) JSON ¶
JSON decodes the response body as JSON into v.
Example:
var user User
if err := resp.JSON(&user); err != nil {
log.Fatal(err)
}
func (*Response) Location ¶
Location returns the Location header value, typically used in redirects.
func (*Response) Raw ¶
Raw returns the underlying *http.Response. Use this when you need access to the full standard library response.
func (*Response) StatusCode ¶
StatusCode returns the HTTP status code.
type ResponseHook ¶
ResponseHook is a function called for every response.
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the maximum number of attempts (including the initial request).
// Default: 3
MaxAttempts int
// InitialDelay is the initial delay between retries.
// Default: 1 second
InitialDelay time.Duration
// MaxDelay is the maximum delay between retries.
// Default: 30 seconds
MaxDelay time.Duration
// Multiplier is the factor by which the delay increases after each retry.
// Default: 2.0 (exponential backoff)
Multiplier float64
// Jitter adds randomness to the delay to prevent thundering herd.
// Default: true
Jitter bool
// RetryIf is a custom function to determine if a request should be retried.
// If nil, the default retry logic is used.
RetryIf func(statusCode int, err error) bool
}
RetryConfig configures the retry behavior.
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns the default retry configuration.
func NewRetryConfig ¶
func NewRetryConfig(opts ...RetryOption) *RetryConfig
NewRetryConfig creates a new RetryConfig with the given options.
func (*RetryConfig) GetDelay ¶
func (c *RetryConfig) GetDelay(attempt int) time.Duration
GetDelay calculates the delay for the given attempt number (0-indexed).
func (*RetryConfig) ShouldRetry ¶
func (c *RetryConfig) ShouldRetry(statusCode int, err error) bool
ShouldRetry determines if the request should be retried based on status code and error.
type RetryOption ¶
type RetryOption func(*RetryConfig)
RetryOption is a function that modifies RetryConfig.
func WithInitialDelay ¶
func WithInitialDelay(d time.Duration) RetryOption
WithInitialDelay sets the initial delay between retries.
func WithJitter ¶
func WithJitter(enabled bool) RetryOption
WithJitter enables or disables jitter in retry delays.
func WithMaxAttempts ¶
func WithMaxAttempts(n int) RetryOption
WithMaxAttempts sets the maximum number of retry attempts.
func WithMaxDelay ¶
func WithMaxDelay(d time.Duration) RetryOption
WithMaxDelay sets the maximum delay between retries.
func WithMultiplier ¶
func WithMultiplier(m float64) RetryOption
WithMultiplier sets the delay multiplier for exponential backoff.
func WithRetryIf ¶
func WithRetryIf(fn func(statusCode int, err error) bool) RetryOption
WithRetryIf sets a custom retry condition function.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
advanced
command
Package main demonstrates advanced usage of the httpc library.
|
Package main demonstrates advanced usage of the httpc library. |
|
basic
command
Package main demonstrates basic usage of the httpc library.
|
Package main demonstrates basic usage of the httpc library. |
|
Package mock provides utilities for mocking HTTP responses in tests.
|
Package mock provides utilities for mocking HTTP responses in tests. |