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 ¶
- func AuthHeaders(method, token string) map[string]string
- func CalculateBackoff(config BackoffConfig, attempt int) time.Duration
- func CommonHTTPHeaders() map[string]string
- func IsRetryableError(err error) bool
- func NewJSONRequest(method, url string, body interface{}) (*http.Request, error)
- func ProcessJSONResponse(resp *http.Response, target interface{}) error
- func ProcessResponse(resp *http.Response) ([]byte, error)
- type APIError
- type BackoffConfig
- type ClientMetrics
- type DefaultConfigProvider
- type ErrorResponse
- type HTTPClient
- func (c *HTTPClient) Do(ctx context.Context, req *http.Request) (*http.Response, error)
- func (c *HTTPClient) DoJSON(ctx context.Context, method, url string, body interface{}) (*http.Response, error)
- func (c *HTTPClient) DoWithFullResponse(ctx context.Context, req *http.Request) (string, *http.Response, error)
- func (c *HTTPClient) GetMetrics() ClientMetrics
- func (c *HTTPClient) PostJSON(ctx context.Context, url string, body interface{}) (*http.Response, error)
- func (c *HTTPClient) ResetMetrics()
- type HTTPClientBuilder
- func (b *HTTPClientBuilder) Build() *HTTPClient
- func (b *HTTPClientBuilder) WithHeaders(headers map[string]string) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithMetrics(enabled bool) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithRequestInterceptor(interceptor RequestInterceptor) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithResponseInterceptor(interceptor ResponseInterceptor) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithRetry(maxRetries int, baseDelay time.Duration) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithTimeout(timeout time.Duration) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithUserAgent(userAgent string) *HTTPClientBuilder
- type HTTPClientConfig
- type RequestBuilder
- func (rb *RequestBuilder) Build() (*http.Request, error)
- func (rb *RequestBuilder) WithContext(ctx context.Context) *RequestBuilder
- func (rb *RequestBuilder) WithHeader(key, value string) *RequestBuilder
- func (rb *RequestBuilder) WithHeaders(headers map[string]string) *RequestBuilder
- func (rb *RequestBuilder) WithJSONBody(body interface{}) *RequestBuilder
- type RequestInterceptor
- type ResponseInterceptor
- type RetryHandler
- type StreamingResponse
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthHeaders ¶
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 ¶
CommonHTTPHeaders returns commonly used HTTP headers for AI providers
func IsRetryableError ¶
IsRetryableError checks if an error should trigger a retry
func NewJSONRequest ¶
NewJSONRequest creates a JSON HTTP request with proper headers
func ProcessJSONResponse ¶
ProcessJSONResponse processes an HTTP response and unmarshals JSON
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 ParseAPIError ¶
ParseAPIError creates a standardized API error from response
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) 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 ¶
RequestInterceptor allows modifying requests before sending
type ResponseInterceptor ¶
ResponseInterceptor allows processing responses after receiving
type RetryHandler ¶
type RetryHandler struct {
// contains filtered or unexported fields
}
RetryHandler manages retry logic with exponential backoff
type StreamingResponse ¶
type StreamingResponse struct {
// contains filtered or unexported fields
}
StreamingResponse handles streaming responses
func NewStreamingResponse ¶
func NewStreamingResponse(resp *http.Response) *StreamingResponse
NewStreamingResponse creates a new streaming response handler
func (*StreamingResponse) Close ¶
func (sr *StreamingResponse) Close() error
Close closes the streaming response
func (*StreamingResponse) ReadChunk ¶
func (sr *StreamingResponse) ReadChunk(delimiter string) ([]byte, error)
ReadChunk reads data until a delimiter
func (*StreamingResponse) ReadLine ¶
func (sr *StreamingResponse) ReadLine() ([]byte, error)
ReadLine reads a single line from the streaming response