http

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2025 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package http provides HTTP client functionality for NuGet protocol operations.

It wraps the standard http.Client with NuGet-specific configuration including configurable timeouts, user agent management, and HTTP/2 support.

Index

Constants

View Source
const (
	// DefaultTimeout is the default HTTP request timeout.
	DefaultTimeout = 30 * time.Second
	// DefaultDialTimeout is the default TCP connection timeout.
	DefaultDialTimeout = 10 * time.Second
	// DefaultUserAgent is the default User-Agent header value.
	DefaultUserAgent = "gonuget/0.1.0"
)
View Source
const (
	// DefaultMaxRetries is the default maximum number of retry attempts.
	DefaultMaxRetries = 3
	// DefaultInitialBackoff is the default initial backoff duration.
	DefaultInitialBackoff = 1 * time.Second
	// DefaultMaxBackoff is the default maximum backoff duration.
	DefaultMaxBackoff = 30 * time.Second
	// DefaultBackoffFactor is the default backoff multiplier.
	DefaultBackoffFactor = 2.0
	// DefaultJitterFactor is the default jitter factor for randomization.
	DefaultJitterFactor = 0.1
)
View Source
const (
	// DefaultRedirectCacheTTL is the default TTL for redirect cache (24 hours)
	DefaultRedirectCacheTTL = 24 * time.Hour
)

Variables

This section is empty.

Functions

func ClearRedirectDiskCache

func ClearRedirectDiskCache() error

ClearRedirectDiskCache removes all cached redirects (for testing).

func GetCachedRedirect

func GetCachedRedirect(sourceURL string) (string, bool)

GetCachedRedirect retrieves a cached redirect target. Returns final URL and true if found and not expired.

func IsRetriable

func IsRetriable(err error) bool

IsRetriable determines if an error should be retried

func IsRetriableStatus

func IsRetriableStatus(code int) bool

IsRetriableStatus determines if an HTTP status code should be retried

func NewDefaultHTTPClient

func NewDefaultHTTPClient() *http.Client

NewDefaultHTTPClient creates an HTTP client with default configuration

func NewHTTPClient

func NewHTTPClient(config TransportConfig) *http.Client

NewHTTPClient creates an HTTP client with configured transport

func NewTransport

func NewTransport(config TransportConfig) http.RoundTripper

NewTransport creates an HTTP transport with configured protocol support

func ParseRetryAfter

func ParseRetryAfter(headerValue string) time.Duration

ParseRetryAfter parses the Retry-After header value Returns duration to wait, or 0 if header is invalid/missing Supports both delay-seconds (int) and HTTP-date formats

func ProtocolVersion

func ProtocolVersion(resp *http.Response) string

ProtocolVersion returns the HTTP protocol version from response

func ResetGlobalClient

func ResetGlobalClient()

ResetGlobalClient resets the global client (for testing only). WARNING: This should only be used in tests.

func ResetRedirectCache

func ResetRedirectCache()

ResetRedirectCache clears the redirect cache (for testing only).

func SetCachedRedirect

func SetCachedRedirect(sourceURL, targetURL string) error

SetCachedRedirect stores a redirect target with 24h TTL.

Types

type Client

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

Client wraps http.Client with NuGet-specific configuration

func GetGlobalClient

func GetGlobalClient() *Client

GetGlobalClient returns the global singleton HTTP client. This client is shared across all NuGet operations for maximum connection reuse. Matches NuGet.Client's HttpHandlerResourceV3Provider behavior where a single HttpClient instance is reused across all package sources.

func NewClient

func NewClient(cfg *Config) *Client

NewClient creates a new HTTP client with the given configuration

func NewClientWithOptions

func NewClientWithOptions(opts ...Option) *Client

NewClientWithOptions creates a client with functional options

func (*Client) Do

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

Do executes an HTTP request with context and user agent

func (*Client) DoWithRetry

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

DoWithRetry executes an HTTP request with retry logic

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) (*http.Response, error)

Get performs a GET request

func (*Client) ResolveRedirect

func (c *Client) ResolveRedirect(ctx context.Context, url string) (string, error)

ResolveRedirect follows redirects and caches the final destination. This eliminates redirect overhead on subsequent requests. Critical for NuGet V2 which redirects downloads from www.nuget.org to globalcdn.nuget.org

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(ua string)

SetUserAgent updates the client's user agent string

type Config

type Config struct {
	Timeout              time.Duration
	DialTimeout          time.Duration
	UserAgent            string
	TLSConfig            *tls.Config
	MaxIdleConns         int
	EnableHTTP2          bool
	RetryConfig          *RetryConfig
	Logger               observability.Logger             // Optional logger (nil uses NullLogger)
	EnableTracing        bool                             // Enable OpenTelemetry HTTP tracing
	CircuitBreakerConfig *resilience.CircuitBreakerConfig // Optional circuit breaker config (nil disables)
	RateLimiterConfig    *resilience.TokenBucketConfig    // Optional rate limiter config (nil disables)
}

Config holds HTTP client configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a client configuration with sensible defaults

type Option

type Option func(*Config)

Option is a functional option for configuring the client

func WithMaxIdleConns

func WithMaxIdleConns(n int) Option

WithMaxIdleConns sets the maximum idle connections

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retries

func WithRetryConfig

func WithRetryConfig(retryCfg *RetryConfig) Option

WithRetryConfig sets custom retry configuration

func WithTLSConfig

func WithTLSConfig(tlsCfg *tls.Config) Option

WithTLSConfig sets custom TLS configuration

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the request timeout

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the user agent string

type RetryConfig

type RetryConfig struct {
	MaxRetries     int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
	BackoffFactor  float64
	JitterFactor   float64
}

RetryConfig holds retry behavior configuration

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns retry configuration with sensible defaults

func (*RetryConfig) CalculateBackoff

func (rc *RetryConfig) CalculateBackoff(attempt int) time.Duration

CalculateBackoff computes exponential backoff with jitter

type TransportConfig

type TransportConfig struct {
	// EnableHTTP2 enables HTTP/2 support (default: true)
	EnableHTTP2 bool

	// EnableHTTP3 enables HTTP/3 support (default: false, experimental)
	EnableHTTP3 bool

	// MaxIdleConns controls the maximum number of idle connections
	MaxIdleConns int

	// MaxIdleConnsPerHost controls idle connections per host
	MaxIdleConnsPerHost int

	// IdleConnTimeout is the maximum time an idle connection will remain idle
	IdleConnTimeout time.Duration

	// TLSHandshakeTimeout is the maximum time for TLS handshake
	TLSHandshakeTimeout time.Duration

	// ResponseHeaderTimeout is the maximum time to wait for response headers
	ResponseHeaderTimeout time.Duration

	// ExpectContinueTimeout is the time to wait for 100-Continue response
	ExpectContinueTimeout time.Duration

	// MaxConnsPerHost limits total connections per host
	MaxConnsPerHost int
}

TransportConfig configures HTTP transport with protocol support

func DefaultTransportConfig

func DefaultTransportConfig() TransportConfig

DefaultTransportConfig returns default transport configuration

Jump to

Keyboard shortcuts

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