http

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package http provides HTTP client utilities and helpers for AI providers.

Package http provides HTTP client utilities and helpers for AI providers. It includes reusable HTTP clients with retry logic, metrics, and interceptors.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthHeaders

func AuthHeaders(method, token string) map[string]string

AuthHeaders creates authentication headers for different methods

func CalculateBackoff added in v1.0.4

func CalculateBackoff(config BackoffConfig, attempt int) time.Duration

CalculateBackoff returns the delay for a given attempt number using exponential backoff attempt is 1-indexed (first retry is attempt 1)

func CommonHTTPHeaders

func CommonHTTPHeaders() map[string]string

CommonHTTPHeaders returns commonly used HTTP headers for AI providers

func NewJSONRequest

func NewJSONRequest(method, url string, body interface{}) (*http.Request, error)

NewJSONRequest creates a JSON HTTP request with proper headers

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Type       string
	Code       string
	RawBody    string
	Timestamp  time.Time
}

APIError represents a standardized API error with context

func (*APIError) Error

func (e *APIError) Error() string

type BackoffConfig added in v1.0.4

type BackoffConfig struct {
	BaseDelay   time.Duration // Initial delay for the first retry
	MaxDelay    time.Duration // Maximum delay cap
	Multiplier  float64       // Exponential multiplier (typically 2.0)
	MaxAttempts int           // Maximum number of retry attempts
}

BackoffConfig configures exponential backoff behavior

func DefaultBackoffConfig added in v1.0.4

func DefaultBackoffConfig() BackoffConfig

DefaultBackoffConfig returns sensible defaults for exponential backoff

type ClientMetrics

type ClientMetrics struct {
	TotalRequests   int64         `json:"total_requests"`
	SuccessfulReqs  int64         `json:"successful_requests"`
	FailedReqs      int64         `json:"failed_requests"`
	AvgLatency      time.Duration `json:"avg_latency"`
	P95Latency      time.Duration `json:"p95_latency"`
	LastRequestTime time.Time     `json:"last_request_time"`
	RetryCount      int64         `json:"retry_count"`
	ErrorsByType    map[int]int64 `json:"errors_by_type"`
}

ClientMetrics tracks HTTP client performance

type DefaultConfigProvider

type DefaultConfigProvider struct{}

DefaultConfigProvider provides configuration for common AI providers

func (*DefaultConfigProvider) GetHTTPConfig

func (d *DefaultConfigProvider) GetHTTPConfig(providerType types.ProviderType) HTTPClientConfig

GetHTTPConfig returns HTTP configuration for different provider types

type ErrorResponse

type ErrorResponse struct {
	Error struct {
		Type    string `json:"type"`
		Message string `json:"message"`
		Code    string `json:"code,omitempty"`
	} `json:"error"`
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorResponse represents a standardized error response

type HTTPClient

type HTTPClient struct {
	// contains filtered or unexported fields
}

HTTPClient provides a reusable HTTP client with common patterns for AI providers

func DefaultClient

func DefaultClient(providerType types.ProviderType) *HTTPClient

DefaultClient creates an HTTP client with sensible defaults for AI providers

func NewHTTPClient

func NewHTTPClient(config HTTPClientConfig) *HTTPClient

NewHTTPClient creates a new HTTP client with common configurations

func (*HTTPClient) Do

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

Do executes an HTTP request with retry logic and metrics

func (*HTTPClient) DoJSON

func (c *HTTPClient) DoJSON(ctx context.Context, method, url string, body interface{}) (*http.Response, error)

DoJSON sends a JSON request with specified method

func (*HTTPClient) DoWithFullResponse

func (c *HTTPClient) DoWithFullResponse(ctx context.Context, req *http.Request) (string, *http.Response, error)

DoWithFullResponse executes request and returns response body as string

func (*HTTPClient) GetMetrics

func (c *HTTPClient) GetMetrics() ClientMetrics

GetMetrics returns current client metrics

func (*HTTPClient) PostJSON

func (c *HTTPClient) PostJSON(ctx context.Context, url string, body interface{}) (*http.Response, error)

PostJSON sends a JSON POST request

func (*HTTPClient) ResetMetrics

func (c *HTTPClient) ResetMetrics()

ResetMetrics resets all metrics

type HTTPClientBuilder

type HTTPClientBuilder struct {
	// contains filtered or unexported fields
}

HTTPClientBuilder provides a builder pattern for HTTPClient

func NewHTTPClientBuilder

func NewHTTPClientBuilder() *HTTPClientBuilder

NewHTTPClientBuilder creates a new builder

func (*HTTPClientBuilder) Build

func (b *HTTPClientBuilder) Build() *HTTPClient

Build creates the HTTP client

func (*HTTPClientBuilder) WithHeaders

func (b *HTTPClientBuilder) WithHeaders(headers map[string]string) *HTTPClientBuilder

WithHeaders sets default headers

func (*HTTPClientBuilder) WithMetrics

func (b *HTTPClientBuilder) WithMetrics(enabled bool) *HTTPClientBuilder

WithMetrics enables metrics collection

func (*HTTPClientBuilder) WithRequestInterceptor

func (b *HTTPClientBuilder) WithRequestInterceptor(interceptor RequestInterceptor) *HTTPClientBuilder

WithRequestInterceptor sets a request interceptor

func (*HTTPClientBuilder) WithResponseInterceptor

func (b *HTTPClientBuilder) WithResponseInterceptor(interceptor ResponseInterceptor) *HTTPClientBuilder

WithResponseInterceptor sets a response interceptor

func (*HTTPClientBuilder) WithRetry

func (b *HTTPClientBuilder) WithRetry(maxRetries int, baseDelay time.Duration) *HTTPClientBuilder

WithRetry sets retry configuration

func (*HTTPClientBuilder) WithTimeout

func (b *HTTPClientBuilder) WithTimeout(timeout time.Duration) *HTTPClientBuilder

WithTimeout sets the timeout

func (*HTTPClientBuilder) WithUserAgent

func (b *HTTPClientBuilder) WithUserAgent(userAgent string) *HTTPClientBuilder

WithUserAgent sets the user agent

type HTTPClientConfig

type HTTPClientConfig struct {
	Timeout             time.Duration       `json:"timeout,omitempty"`
	MaxRetries          int                 `json:"max_retries,omitempty"`
	BaseRetryDelay      time.Duration       `json:"base_retry_delay,omitempty"`
	MaxRetryDelay       time.Duration       `json:"max_retry_delay,omitempty"`
	BackoffMultiplier   float64             `json:"backoff_multiplier,omitempty"`
	RetryableErrors     []string            `json:"retryable_errors,omitempty"`
	Headers             map[string]string   `json:"headers,omitempty"`
	UserAgent           string              `json:"user_agent,omitempty"`
	EnableMetrics       bool                `json:"enable_metrics,omitempty"`
	RequestInterceptor  RequestInterceptor  `json:"-"`
	ResponseInterceptor ResponseInterceptor `json:"-"`
}

HTTPClientConfig configures the HTTP client

type RequestBuilder

type RequestBuilder struct {
	// contains filtered or unexported fields
}

RequestBuilder helps build HTTP requests with common patterns

func NewRequestBuilder

func NewRequestBuilder(method, url string) *RequestBuilder

NewRequestBuilder creates a new request builder

func (*RequestBuilder) Build

func (rb *RequestBuilder) Build() (*http.Request, error)

Build creates the HTTP request

func (*RequestBuilder) WithContext

func (rb *RequestBuilder) WithContext(ctx context.Context) *RequestBuilder

WithContext sets the request context

func (*RequestBuilder) WithHeader

func (rb *RequestBuilder) WithHeader(key, value string) *RequestBuilder

WithHeader adds a single header

func (*RequestBuilder) WithHeaders

func (rb *RequestBuilder) WithHeaders(headers map[string]string) *RequestBuilder

WithHeaders adds headers to the request

func (*RequestBuilder) WithJSONBody

func (rb *RequestBuilder) WithJSONBody(body interface{}) *RequestBuilder

WithJSONBody sets a JSON body

type RequestInterceptor

type RequestInterceptor interface {
	Intercept(req *http.Request) error
}

RequestInterceptor allows modifying requests before sending

type ResponseInterceptor

type ResponseInterceptor interface {
	Intercept(resp *http.Response) error
}

ResponseInterceptor allows processing responses after receiving

type RetryHandler

type RetryHandler struct {
	// contains filtered or unexported fields
}

RetryHandler manages retry logic with exponential backoff

Jump to

Keyboard shortcuts

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