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.
Example (BuilderWithTransport) ¶
Example_builderWithTransport demonstrates using the builder pattern with transport configuration
package main
import (
"context"
"fmt"
"net/http"
"time"
httputil "github.com/cecil-the-coder/ai-provider-kit/internal/http"
)
func main() {
client := httputil.NewHTTPClientBuilder().
WithTimeout(30*time.Second).
WithRetry(3, time.Second).
WithTransportConfig(300, 30, 100).
WithIdleConnTimeout(60 * time.Second).
WithTLSHandshakeTimeout(5 * time.Second).
Build()
req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
resp, err := client.Do(context.Background(), req)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
defer func() { _ = resp.Body.Close() }() //nolint:errcheck // Example code
fmt.Printf("Status: %d\n", resp.StatusCode)
}
Output:
Example (CustomTransportConfig) ¶
Example_customTransportConfig demonstrates creating an HTTP client with custom connection pool settings
package main
import (
"context"
"fmt"
"net/http"
"time"
httputil "github.com/cecil-the-coder/ai-provider-kit/internal/http"
)
func main() {
client := httputil.NewHTTPClient(httputil.HTTPClientConfig{
Timeout: 30 * time.Second,
MaxIdleConns: 200,
MaxIdleConnsPerHost: 20,
MaxConnsPerHost: 50,
IdleConnTimeout: 120 * time.Second,
TLSHandshakeTimeout: 15 * time.Second,
})
req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
resp, err := client.Do(context.Background(), req)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
defer func() { _ = resp.Body.Close() }() //nolint:errcheck // Example code
fmt.Printf("Status: %d\n", resp.StatusCode)
}
Output:
Example (DefaultClient) ¶
Example_defaultClient demonstrates creating an HTTP client with default transport settings
package main
import (
"context"
"fmt"
"net/http"
"time"
httputil "github.com/cecil-the-coder/ai-provider-kit/internal/http"
)
func main() {
client := httputil.NewHTTPClient(httputil.HTTPClientConfig{
Timeout: 30 * time.Second,
})
req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
resp, err := client.Do(context.Background(), req)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
defer func() { _ = resp.Body.Close() }() //nolint:errcheck // Example code
fmt.Printf("Status: %d\n", resp.StatusCode)
}
Output:
Example (HighConcurrencyClient) ¶
Example_highConcurrencyClient demonstrates creating a client optimized for high concurrency
package main
import (
"context"
"fmt"
"net/http"
"time"
httputil "github.com/cecil-the-coder/ai-provider-kit/internal/http"
)
func main() {
// High concurrency client with 500 max idle connections
client := httputil.NewHighConcurrencyHTTPClient(httputil.HTTPClientConfig{
Timeout: 10 * time.Second,
MaxRetries: 3,
})
req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
resp, err := client.Do(context.Background(), req)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
defer func() { _ = resp.Body.Close() }() //nolint:errcheck // Example code
fmt.Printf("Status: %d\n", resp.StatusCode)
}
Output:
Index ¶
- func AuthHeaders(method, token string) map[string]string
- func CalculateBackoff(config BackoffConfig, attempt int) time.Duration
- func CommonHTTPHeaders() map[string]string
- func NewJSONRequest(method, url string, body interface{}) (*http.Request, error)
- type APIError
- type BackoffConfig
- type ClientMetrics
- type DefaultConfigProvider
- type ErrorResponse
- type HTTPClient
- func (c *HTTPClient) Client() *http.Client
- 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) WithExpectContinueTimeout(timeout time.Duration) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithHeaders(headers map[string]string) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithIdleConnTimeout(timeout time.Duration) *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) WithTLSHandshakeTimeout(timeout time.Duration) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithTimeout(timeout time.Duration) *HTTPClientBuilder
- func (b *HTTPClientBuilder) WithTransportConfig(maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost int) *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
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthHeaders ¶
AuthHeaders creates authentication headers for different methods
func CalculateBackoff ¶
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
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
type BackoffConfig ¶
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 ¶
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 NewHighConcurrencyHTTPClient ¶ added in v1.0.40
func NewHighConcurrencyHTTPClient(config HTTPClientConfig) *HTTPClient
NewHighConcurrencyHTTPClient creates an HTTP client optimized for high-concurrency scenarios. It uses increased connection pool limits suitable for applications making many parallel requests.
func (*HTTPClient) Client ¶ added in v1.0.40
func (c *HTTPClient) Client() *http.Client
Client returns the underlying http.Client
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) WithExpectContinueTimeout ¶ added in v1.0.40
func (b *HTTPClientBuilder) WithExpectContinueTimeout(timeout time.Duration) *HTTPClientBuilder
WithExpectContinueTimeout sets the expect continue timeout
func (*HTTPClientBuilder) WithHeaders ¶
func (b *HTTPClientBuilder) WithHeaders(headers map[string]string) *HTTPClientBuilder
WithHeaders sets default headers
func (*HTTPClientBuilder) WithIdleConnTimeout ¶ added in v1.0.40
func (b *HTTPClientBuilder) WithIdleConnTimeout(timeout time.Duration) *HTTPClientBuilder
WithIdleConnTimeout sets the idle connection timeout
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) WithTLSHandshakeTimeout ¶ added in v1.0.40
func (b *HTTPClientBuilder) WithTLSHandshakeTimeout(timeout time.Duration) *HTTPClientBuilder
WithTLSHandshakeTimeout sets the TLS handshake timeout
func (*HTTPClientBuilder) WithTimeout ¶
func (b *HTTPClientBuilder) WithTimeout(timeout time.Duration) *HTTPClientBuilder
WithTimeout sets the timeout
func (*HTTPClientBuilder) WithTransportConfig ¶ added in v1.0.40
func (b *HTTPClientBuilder) WithTransportConfig(maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost int) *HTTPClientBuilder
WithTransportConfig sets transport configuration for connection pooling
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:"-"`
// Transport configuration
MaxIdleConns int `json:"max_idle_conns,omitempty"`
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host,omitempty"`
MaxConnsPerHost int `json:"max_conns_per_host,omitempty"`
IdleConnTimeout time.Duration `json:"idle_conn_timeout,omitempty"`
TLSHandshakeTimeout time.Duration `json:"tls_handshake_timeout,omitempty"`
ExpectContinueTimeout time.Duration `json:"expect_continue_timeout,omitempty"`
}
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