httpclient

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: GPL-3.0 Imports: 5 Imported by: 0

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...
}
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...
}
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...
}

Index

Examples

Constants

View Source
const (
	DefaultRetryCount = RetryCount(10)
	DefaultTimeout    = 60 * time.Second
	DefaultWaitMin    = 1 * time.Second
	DefaultWaitMax    = 60 * time.Second
)

Default configs.

Variables

View Source
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.

View Source
var DefaultRetryConfig = RetryConfig{
	MaxRetries: DefaultRetryCount,
	WaitMin:    DefaultWaitMin,
	WaitMax:    DefaultWaitMax,
}

DefaultRetryConfig provides sensible retry defaults for most HTTP clients.

View Source
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.

func (*AuthTransport) RoundTrip

func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

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

func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error)

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

func (c *Client) Standard() *http.Client

Standard exposes an *http.Client configured consistently with the retryable client.

func (*Client) WithAuthToken

func (c *Client) WithAuthToken(t Token) *Client

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

func (c *Client) WithTracing() *Client

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 RetryAttempt

type RetryAttempt int

RetryAttempt represents the current retry attempt number.

func (RetryAttempt) ToInt

func (a RetryAttempt) ToInt() int

ToInt converts RetryAttempt to int.

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.

func (RetryCount) ToInt

func (c RetryCount) ToInt() int

ToInt converts a RetryCount to int.

type TimeoutConfig

type TimeoutConfig struct {
	HTTPTimeout time.Duration
}

TimeoutConfig defines HTTP timeout behavior.

type Token

type Token string

Token represents an authentication token for HTTP requests.

func (Token) ToString

func (t Token) ToString() string

ToString returns the raw string value of a Token.

Jump to

Keyboard shortcuts

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