Documentation
¶
Overview ¶
Example (Basic) ¶
Example demonstrates basic usage of the HTTP client with default settings.
package main
import (
"context"
"net/http"
"github.com/grhili/cd-operator/pkg/httpclient"
)
func main() {
// Create a new client with defaults (10 retries, 60s timeout, 1-60s backoff)
client := httpclient.NewClient()
// Create a standard HTTP request
req, _ := http.NewRequest(http.MethodGet, "https://api.example.com/data", nil)
// Execute the request with context
ctx := context.Background()
resp, err := client.Do(ctx, req)
if err != nil {
// Handle error
return
}
defer resp.Body.Close()
// Use response...
}
Output:
Example (WithCustomBackoff) ¶
Example demonstrates custom backoff strategy.
package main
import (
"context"
"net/http"
"time"
"github.com/grhili/cd-operator/pkg/httpclient"
)
func main() {
// Create client with exponential backoff
client := httpclient.NewClient().
WithBackoff(httpclient.BackoffConfig{
Backoff: func(min, max time.Duration, attempt httpclient.RetryAttempt, resp *http.Response) time.Duration {
// Exponential backoff: wait = 2^attempt * min
wait := time.Duration(1<<uint(attempt.ToInt())) * min
if wait > max {
return max
}
return wait
},
})
req, _ := http.NewRequest(http.MethodGet, "https://api.example.com/data", nil)
ctx := context.Background()
resp, err := client.Do(ctx, req)
if err != nil {
// Handle error
return
}
defer resp.Body.Close()
// Use response...
}
Output:
Example (WithCustomConfig) ¶
Example demonstrates fluent API with custom configuration.
package main
import (
"context"
"net/http"
"time"
"github.com/grhili/cd-operator/pkg/httpclient"
)
func main() {
// Create client with custom settings using fluent API
client := httpclient.NewClient().
WithAuthToken(httpclient.Token("your-bearer-token")).
WithRetry(httpclient.RetryConfig{
MaxRetries: httpclient.RetryCount(5),
WaitMin: 2 * time.Second,
WaitMax: 30 * time.Second,
}).
WithTimeout(httpclient.TimeoutConfig{
HTTPTimeout: 30 * time.Second,
})
// Create request
req, _ := http.NewRequest(http.MethodPost, "https://api.example.com/create", nil)
// Execute with context
ctx := context.Background()
resp, err := client.Do(ctx, req)
if err != nil {
// Handle error
return
}
defer resp.Body.Close()
// Use response...
}
Output:
Index ¶
- Constants
- Variables
- type AuthTransport
- type BackoffConfig
- type BackoffFunc
- type Client
- func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error)
- func (c *Client) Retryable() *retryablehttp.Client
- func (c *Client) Standard() *http.Client
- func (c *Client) WithAuthToken(t Token) *Client
- func (c *Client) WithBackoff(cfg BackoffConfig) *Client
- func (c *Client) WithLogger(l LeveledLogger) *Client
- func (c *Client) WithRetry(cfg RetryConfig) *Client
- func (c *Client) WithTimeout(cfg TimeoutConfig) *Client
- func (c *Client) WithTracing() *Client
- type LeveledLogger
- type RetryAttempt
- type RetryConfig
- type RetryCount
- type TimeoutConfig
- type Token
Examples ¶
Constants ¶
const ( DefaultRetryCount = RetryCount(10) DefaultTimeout = 60 * time.Second DefaultWaitMin = 1 * time.Second DefaultWaitMax = 60 * time.Second )
Default configs.
Variables ¶
var DefaultBackoffConfig = BackoffConfig{ Backoff: func(min, max time.Duration, attempt RetryAttempt, _ *http.Response) time.Duration { wait := time.Duration(attempt.ToInt()) * min if wait > max { return max } return wait }, }
DefaultBackoffConfig provides a linear backoff strategy.
var DefaultRetryConfig = RetryConfig{ MaxRetries: DefaultRetryCount, WaitMin: DefaultWaitMin, WaitMax: DefaultWaitMax, }
DefaultRetryConfig provides sensible retry defaults for most HTTP clients.
var DefaultTimeoutConfig = TimeoutConfig{ HTTPTimeout: DefaultTimeout, }
DefaultTimeoutConfig provides sensible timeout defaults for most HTTP clients.
Functions ¶
This section is empty.
Types ¶
type AuthTransport ¶
type AuthTransport struct {
// Token holds the bearer token value (without the "Bearer " prefix baked in).
Token Token
// Next is the next RoundTripper in the chain. It must never be nil.
Next http.RoundTripper
// Logger for transport-level operations
Logger LeveledLogger
}
AuthTransport is an http.RoundTripper that injects the Authorization header.
It sits in front of any existing RoundTripper so we do not break other transport concerns like tracing or TLS configuration.
type BackoffConfig ¶
type BackoffConfig struct {
Backoff BackoffFunc
}
BackoffConfig holds backoff strategy information.
type BackoffFunc ¶
type BackoffFunc func(min, max time.Duration, attempt RetryAttempt, resp *http.Response) time.Duration
BackoffFunc defines how long to wait before retrying.
type Client ¶
type Client struct {
// Logger is the high-level logger used by our code.
Logger LeveledLogger
// contains filtered or unexported fields
}
Client wraps a retryable HTTP engine and exposes a typed API while keeping all third-party types unexposed.
func NewClient ¶
func NewClient() *Client
NewClient constructs a retryable HTTP client with sane defaults.
The returned client:
- Has retries, timeout, and backoff preconfigured.
- Uses a no-op logger that callers can override with WithLogger.
- Is ready to be used directly with Do(ctx, req).
func (*Client) Do ¶
Do executes the HTTP request with retry/backoff and respects context cancellation.
func (*Client) Retryable ¶
func (c *Client) Retryable() *retryablehttp.Client
Retryable exposes the underlying retryablehttp.Client for advanced use cases.
func (*Client) Standard ¶
Standard exposes an *http.Client configured consistently with the retryable client.
func (*Client) WithAuthToken ¶
WithAuthToken injects authentication into the existing transport chain.
This keeps all auth behavior in the HTTP layer and avoids spreading token concerns across the rest of the codebase.
func (*Client) WithBackoff ¶
func (c *Client) WithBackoff(cfg BackoffConfig) *Client
WithBackoff updates the backoff configuration at runtime.
func (*Client) WithLogger ¶
func (c *Client) WithLogger(l LeveledLogger) *Client
WithLogger installs a structured logger into the client and silences the internal retryable http logger by default.
If you want retryable http's own logs, you can adapt your logger into whatever it expects and set c.rc.Logger manually from outside this package.
func (*Client) WithRetry ¶
func (c *Client) WithRetry(cfg RetryConfig) *Client
WithRetry updates the retry configuration at runtime.
We keep a copy of the config so callers can inspect the current state if needed.
func (*Client) WithTimeout ¶
func (c *Client) WithTimeout(cfg TimeoutConfig) *Client
WithTimeout updates the timeout configuration at runtime.
func (*Client) WithTracing ¶
WithTracing wraps the HTTP transport with OpenTelemetry instrumentation. This enables automatic span creation for HTTP requests with trace propagation. Call this method after creating the client to enable distributed tracing.
Example:
client := httpclient.NewClient().WithTracing()
type LeveledLogger ¶
type LeveledLogger interface {
Debug(msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Warn(msg string, keysAndValues ...interface{})
Error(msg string, keysAndValues ...interface{})
}
LeveledLogger defines the structured logging behavior expected by this client. This interface is compatible with zap.SugaredLogger.
func NewNoOpLogger ¶
func NewNoOpLogger() LeveledLogger
NewNoOpLogger creates a no-op logger that silently discards all log messages.
type RetryConfig ¶
type RetryConfig struct {
MaxRetries RetryCount
WaitMin time.Duration
WaitMax time.Duration
}
RetryConfig defines typed retry behavior.
type RetryCount ¶
type RetryCount int
RetryCount represents a typed retry count instead of a raw int.
type TimeoutConfig ¶
TimeoutConfig defines HTTP timeout behavior.