connection

package
v1.7.3 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package connection manages HTTP connection pooling, TLS configuration, and proxy detection for the httpc library.

Index

Constants

This section is empty.

Variables

View Source
var ErrPoolExhausted = errors.New("connection pool exhausted")

ErrPoolExhausted is returned when the connection pool has reached its maximum capacity and cannot accept new connections. Callers can detect this condition with errors.Is(err, connection.ErrPoolExhausted).

View Source
var ErrProxyConnectionFailed = errors.New("proxy connection failed")

ErrProxyConnectionFailed wraps errors that occur while connecting to a proxy server (dial failure, invalid address, refused connection, etc.). The retry engine checks for this sentinel when proxy rotation is active to decide whether to retry with the next proxy in the pool.

Functions

func AllowPrivateIPsOverrideFromContext added in v1.5.2

func AllowPrivateIPsOverrideFromContext(ctx context.Context) (allow bool, ok bool)

AllowPrivateIPsOverrideFromContext reports the per-request AllowPrivateIPs override carried on ctx. The ok result is false when no override is present, in which case callers fall back to the client-level policy.

func WithAllowPrivateIPsOverride added in v1.5.2

func WithAllowPrivateIPsOverride(ctx context.Context, allow bool) context.Context

WithAllowPrivateIPsOverride returns a copy of ctx that carries a per-request AllowPrivateIPs override. When present, the dialer and redirect validator use this value in place of the client-level config. It is intended for internal use by the engine to honor the per-request WithAllowPrivateIPs option.

ctx must be non-nil; callers (the engine) always supply the request context.

func WithProxyAttempt added in v1.6.0

func WithProxyAttempt(ctx context.Context, attempt int) context.Context

WithProxyAttempt returns a copy of ctx that carries the retry-attempt index. When present, the proxy selector uses Pool.SelectIndex(attempt) instead of the round-robin Pool.Select, ensuring each retry attempt deterministically lands on a different proxy even when redirect-following within a single attempt consumes extra Select calls.

ctx must be non-nil; callers (the engine) always supply the request context.

func WithProxyRecorder added in v1.6.3

func WithProxyRecorder(ctx context.Context, rec *ProxyRecorder) context.Context

WithProxyRecorder returns a copy of ctx that carries the proxy recorder. The engine calls this once per request before execution; the transport's Proxy callback then writes into rec for every attempt of that request.

Types

type CertPinner added in v1.3.8

type CertPinner interface {
	VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
}

CertPinner defines the interface for certificate pinning. It is the exported counterpart of the former unexported certPinner type, so the engine can plumb the public security.CertificatePinner through Config as a normal field instead of the SetCertPinner side channel (see buildConnectionConfig).

security.CertificatePinner (which adds a Pin() string method) is a superset of this interface, so a pinner built with the public constructors assigns directly to Config.CertPinner with no adapter.

type Config

type Config struct {
	MaxIdleConns        int
	MaxIdleConnsPerHost int
	MaxConnsPerHost     int
	MaxTotalConns       int

	DialTimeout            time.Duration
	KeepAlive              time.Duration
	TLSHandshakeTimeout    time.Duration
	ResponseHeaderTimeout  time.Duration
	IdleConnTimeout        time.Duration
	ExpectContinueTimeout  time.Duration
	MaxResponseHeaderBytes int64

	TLSConfig          *tls.Config
	MinTLSVersion      uint16
	MaxTLSVersion      uint16
	InsecureSkipVerify bool

	EnableHTTP2 bool
	ProxyURL    string

	// System proxy configuration
	EnableSystemProxy bool // Automatically detect and use system proxy settings

	// Proxy pool configuration. When set, requests are distributed across the
	// listed proxies with passive circuit breaking. Lower priority than
	// ProxyURL, higher than EnableSystemProxy.
	ProxyPool             []string
	ProxyPoolStrategy     proxypool.Strategy
	ProxyFailureThreshold int
	ProxyCooldown         time.Duration

	// EnableProxyPoolHTTP2 routes pool traffic through one dedicated transport
	// per proxy (each with its own HTTP/2 pool) instead of forcing HTTP/1 on
	// the shared transport. See NewPoolManager's dispatcher activation for the
	// exact conditions and pool.go's force-HTTP/1 comment for the rationale.
	EnableProxyPoolHTTP2 bool

	AllowPrivateIPs bool

	ExemptNets []*net.IPNet

	DisableKeepAlives bool
	ForceAttemptHTTP2 bool

	CookieJar http.CookieJar

	// DNS configuration
	EnableDoH   bool          // Enable DNS-over-HTTPS
	DoHCacheTTL time.Duration // DoH cache TTL

	// Certificate pinning
	CertPinner CertPinner
}

Config defines connection pool configuration. Treated as immutable once passed to NewPoolManager: scalar fields are frozen via a shallow copy at construction; reference fields (ProxyPool, ExemptNets, TLSConfig, CookieJar) are shared and must not be mutated afterwards.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns optimized default configuration.

type Metrics

type Metrics struct {
	ActiveConnections   int64
	TotalConnections    int64
	RejectedConnections int64
	ConnectionHitRate   float64
	LastUpdate          int64
}

metrics provides connection pool performance metrics.

TotalConnections is the cumulative count of successfully established connections (monotonic); the current number of open connections is ActiveConnections. ConnectionHitRate = Total/(Total+Rejected), i.e. the share of dial attempts the pool admitted (the old implementation mixed the live-connection gauge with the monotonic rejection counter, making the rate drift and jitter).

type PoolManager

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

PoolManager provides intelligent connection pool management with monitoring

func NewPoolManager

func NewPoolManager(config *Config) (*PoolManager, error)

NewPoolManager creates a new connection pool manager with the given configuration.

func (*PoolManager) Close

func (pm *PoolManager) Close() error

Close releases the PoolManager's resources, including the DoH resolver and the shared transport. It is safe to call multiple times; subsequent calls are no-ops. Returns any error encountered while closing sub-components.

func (*PoolManager) CloseIdleConnections added in v1.6.0

func (pm *PoolManager) CloseIdleConnections()

CloseIdleConnections closes all idle connections in the underlying transport. Used by the retry layer to force the transport to re-evaluate transport.Proxy on the next request — without this, HTTP/2 connection reuse through a CONNECT tunnel can bypass Proxy() and reuse the connection from a previous attempt, defeating proxy rotation. Per-proxy dispatcher transports are swept too.

func (*PoolManager) DoHLookup added in v1.7.3

func (pm *PoolManager) DoHLookup() func(ctx context.Context, host string) ([]net.IPAddr, error)

DoHLookup returns the DoH resolver's lookup, or nil (system resolver) when DoH is disabled. Every resolution-based check must use the SAME resolver as the dial path or the layers can disagree on what a hostname resolves to (DoH says public, system DNS says private) and reject requests the dial path would have allowed — or vice versa. Consumers: the standard path's proxied-target SSRF guard and the fingerprint transport (preflight + the validating direct dialer), both fed through Config plumbing.

func (*PoolManager) GetMetrics

func (pm *PoolManager) GetMetrics() Metrics

GetMetrics returns a snapshot of current connection pool statistics, including active, total, and rejected connection counts and the connection hit rate. The returned Metrics type is exported so a future public metrics API can name it (an exported method returning an unexported type is a dead end — consumers cannot spell the return type).

func (*PoolManager) GetRoundTripper added in v1.7.1

func (pm *PoolManager) GetRoundTripper() http.RoundTripper

GetRoundTripper returns the RoundTripper requests should be sent through: the per-proxy dispatcher when EnableProxyPoolHTTP2 is active, otherwise the shared transport. The engine installs this as the http.Client's Transport.

func (*PoolManager) GetTransport

func (pm *PoolManager) GetTransport() *http.Transport

GetTransport returns the shared *http.Transport used for pooled connections.

func (*PoolManager) HasProxy added in v1.6.3

func (pm *PoolManager) HasProxy() bool

HasProxy reports whether requests are routed through an explicitly configured proxy — a manual ProxyURL or a proxy pool. System-proxy detection is not covered because its selection is resolved dynamically per request. The engine uses this to attach a ProxyRecorder only when a proxy may be selected, keeping the direct-connection path allocation-free.

func (*PoolManager) NextProxyIndex added in v1.6.0

func (pm *PoolManager) NextProxyIndex() (int, bool)

NextProxyIndex advances the proxy pool's round-robin cursor once and returns the resulting base index. The caller (retry engine) combines this with the attempt number (base + attempt) to deterministically select a different proxy per retry, while still rotating across sequential requests. Returns (0, false) when no proxy pool is configured.

func (*PoolManager) ReportProxyFailure added in v1.7.0

func (pm *PoolManager) ReportProxyFailure(addr string)

ReportProxyFailure records a connection-level failure against the proxy at addr (canonical host:port), advancing its circuit breaker. Intended for transports that dial outside this package; the standard dialer reports internally.

func (*PoolManager) ReportProxySuccess added in v1.7.0

func (pm *PoolManager) ReportProxySuccess(addr string)

ReportProxySuccess clears the failure streak of the proxy at addr after a successful request. See ReportProxyFailure.

func (*PoolManager) SelectProxy added in v1.7.0

func (pm *PoolManager) SelectProxy(ctx context.Context, targetURL *url.URL) (*url.URL, error)

SelectProxy returns the proxy URL that applies to a request for targetURL, applying the same selection logic the standard transport path uses: the per-attempt index (WithProxyAttempt) and ProxyRecorder carried on ctx are honored, so proxy-pool rotation and per-request reporting behave identically for external transports. Returns (nil, nil) for a direct connection.

ctx must be non-nil; callers typically pass the request context.

type ProxyRecorder added in v1.6.3

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

ProxyRecorder captures the proxy URL chosen by the transport's Proxy callback for a single logical request. net/http invokes the Proxy callback on every request — including redirects and idle-connection reuse — so the value recorded after an attempt completes is the proxy that actually carried it. A zero value is ready to use and safe for concurrent access.

func (*ProxyRecorder) Last added in v1.6.3

func (p *ProxyRecorder) Last() string

Last returns the most recently recorded proxy URL, or "" when no proxy was selected for the request (direct connection, or no recorder attached).

Jump to

Keyboard shortcuts

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