transport

package
v1.5.9 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CacheKeyPrefixSession = "httpcloak:sessions"
	CacheKeyPrefixECH     = "httpcloak:ech"
)

CacheKeyPrefix constants for distributed cache

View Source
const TLSSessionCacheMaxSize = 32

TLSSessionCacheMaxSize is the maximum number of sessions to cache Matches the size used by pool/pool.go for LRU session cache

View Source
const TLSSessionMaxAge = 24 * time.Hour

TLSSessionMaxAge is the maximum age for TLS sessions (24 hours) TLS session tickets typically expire after 24-48 hours

Variables

View Source
var (
	// ErrConnection represents connection-level errors
	ErrConnection = errors.New("connection error")

	// ErrTLS represents TLS/SSL related errors
	ErrTLS = errors.New("TLS error")

	// ErrDNS represents DNS resolution errors
	ErrDNS = errors.New("DNS error")

	// ErrTimeout represents timeout errors
	ErrTimeout = errors.New("timeout error")

	// ErrProxy represents proxy-related errors
	ErrProxy = errors.New("proxy error")

	// ErrProtocol represents protocol negotiation errors
	ErrProtocol = errors.New("protocol error")

	// ErrRequest represents request-level errors
	ErrRequest = errors.New("request error")

	// ErrResponse represents response-level errors
	ErrResponse = errors.New("response error")

	// ErrClosed represents errors when transport is closed
	ErrClosed = errors.New("transport closed")
)

Error categories for better error handling

Functions

func FormatECHCacheKey added in v1.5.8

func FormatECHCacheKey(preset, host, port string) string

FormatECHCacheKey creates a cache key for ECH configs. Format: httpcloak:ech:{preset}:{host}:{port}

func FormatSessionCacheKey added in v1.5.8

func FormatSessionCacheKey(preset, protocol, host, port string) string

FormatSessionCacheKey creates a cache key for TLS sessions. Format: httpcloak:sessions:{preset}:{protocol}:{host}:{port}

func FormatSessionCacheKeyWithID added in v1.5.8

func FormatSessionCacheKeyWithID(sessionId, preset, protocol, host, port string) string

FormatSessionCacheKeyWithID creates a cache key for TLS sessions that includes a session identifier. This is used when sessions need to be isolated per proxy/session (e.g., different upstream proxies). Format: httpcloak:sessions:{sessionId}:{preset}:{protocol}:{host}:{port}

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError checks if an error is a connection error

func IsDNSError

func IsDNSError(err error) bool

IsDNSError checks if an error is a DNS error

func IsMASQUEProxy added in v1.5.2

func IsMASQUEProxy(proxyURL string) bool

IsMASQUEProxy checks if the proxy URL should use MASQUE protocol (exported version). Returns true for masque:// scheme or known MASQUE providers with https://

func IsProxyError

func IsProxyError(err error) bool

IsProxyError checks if an error is a proxy error

func IsSOCKS5Proxy added in v1.5.2

func IsSOCKS5Proxy(proxyURL string) bool

IsSOCKS5Proxy checks if the proxy URL is a SOCKS5 proxy (exported version)

func IsTLSError

func IsTLSError(err error) bool

IsTLSError checks if an error is a TLS error

func IsTimeout

func IsTimeout(err error) bool

IsTimeout checks if an error is a timeout error

func SupportsQUIC added in v1.5.2

func SupportsQUIC(proxyURL string) bool

SupportsQUIC checks if the proxy URL supports QUIC/HTTP3 tunneling. Returns true for SOCKS5 (UDP relay) or MASQUE (CONNECT-UDP) proxies.

func WrapError

func WrapError(op, host, port, protocol string, cause error) error

WrapError wraps an error with transport context

Types

type ConnStats

type ConnStats struct {
	Host           string
	CreatedAt      time.Time
	LastUsedAt     time.Time
	UseCount       int64
	Age            time.Duration
	IdleTime       time.Duration
	IsReused       bool
	SessionResumed bool   // True if TLS session was resumed
	TLSVersion     uint16 // TLS version (e.g., 0x0304 for TLS 1.3)
	CipherSuite    uint16 // Negotiated cipher suite
}

ConnStats contains connection statistics

type ErrorCallback added in v1.5.8

type ErrorCallback func(operation string, key string, err error)

ErrorCallback is called when a backend operation fails. This allows users to handle errors from async backend operations.

type HTTP1ConnStats

type HTTP1ConnStats struct {
	IdleConns      int
	TotalUseCount  int64
	OldestCreated  time.Time
	NewestLastUsed time.Time
}

HTTP1ConnStats contains HTTP/1.1 connection statistics

type HTTP1Transport

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

HTTP1Transport is a custom HTTP/1.1 transport with uTLS fingerprinting and connection pooling with keep-alive support

func NewHTTP1Transport

func NewHTTP1Transport(preset *fingerprint.Preset, dnsCache *dns.Cache) *HTTP1Transport

NewHTTP1Transport creates a new HTTP/1.1 transport with uTLS

func NewHTTP1TransportWithConfig added in v1.5.2

func NewHTTP1TransportWithConfig(preset *fingerprint.Preset, dnsCache *dns.Cache, proxy *ProxyConfig, config *TransportConfig) *HTTP1Transport

NewHTTP1TransportWithConfig creates a new HTTP/1.1 transport with proxy and config

func NewHTTP1TransportWithProxy

func NewHTTP1TransportWithProxy(preset *fingerprint.Preset, dnsCache *dns.Cache, proxy *ProxyConfig) *HTTP1Transport

NewHTTP1TransportWithProxy creates a new HTTP/1.1 transport with optional proxy

func (*HTTP1Transport) Close

func (t *HTTP1Transport) Close()

Close shuts down the transport

func (*HTTP1Transport) GetDNSCache

func (t *HTTP1Transport) GetDNSCache() *dns.Cache

GetDNSCache returns the DNS cache

func (*HTTP1Transport) GetProxy added in v1.5.8

func (t *HTTP1Transport) GetProxy() *ProxyConfig

GetProxy returns the current proxy configuration

func (*HTTP1Transport) GetSessionCache added in v1.5.5

func (t *HTTP1Transport) GetSessionCache() utls.ClientSessionCache

GetSessionCache returns the TLS session cache

func (*HTTP1Transport) RoundTrip

func (t *HTTP1Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper

func (*HTTP1Transport) SetConnectTo added in v1.5.2

func (t *HTTP1Transport) SetConnectTo(requestHost, connectHost string)

SetConnectTo sets a host mapping for domain fronting (stub for HTTP/1.1)

func (*HTTP1Transport) SetInsecureSkipVerify

func (t *HTTP1Transport) SetInsecureSkipVerify(skip bool)

SetInsecureSkipVerify sets whether to skip TLS verification

func (*HTTP1Transport) SetProxy added in v1.5.8

func (t *HTTP1Transport) SetProxy(proxy *ProxyConfig)

SetProxy changes the proxy configuration and closes all existing connections HTTP/1.1 connections are short-lived, but we close idle ones for cleanliness

func (*HTTP1Transport) SetSessionCache added in v1.5.5

func (t *HTTP1Transport) SetSessionCache(cache utls.ClientSessionCache)

SetSessionCache sets the TLS session cache

func (*HTTP1Transport) Stats

func (t *HTTP1Transport) Stats() map[string]HTTP1ConnStats

Stats returns transport statistics

func (*HTTP1Transport) StreamRoundTrip added in v1.5.3

func (t *HTTP1Transport) StreamRoundTrip(req *http.Request) (*http.Response, error)

StreamRoundTrip performs an HTTP request for streaming - connection is NOT pooled The connection will be closed when the response body is closed

type HTTP2Transport

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

HTTP2Transport is a custom HTTP/2 transport with uTLS fingerprinting and proper connection reuse

func NewHTTP2Transport

func NewHTTP2Transport(preset *fingerprint.Preset, dnsCache *dns.Cache) *HTTP2Transport

NewHTTP2Transport creates a new HTTP/2 transport with uTLS

func NewHTTP2TransportWithConfig added in v1.5.2

func NewHTTP2TransportWithConfig(preset *fingerprint.Preset, dnsCache *dns.Cache, proxy *ProxyConfig, config *TransportConfig) *HTTP2Transport

NewHTTP2TransportWithConfig creates a new HTTP/2 transport with proxy and advanced config

func NewHTTP2TransportWithProxy

func NewHTTP2TransportWithProxy(preset *fingerprint.Preset, dnsCache *dns.Cache, proxy *ProxyConfig) *HTTP2Transport

NewHTTP2TransportWithProxy creates a new HTTP/2 transport with optional proxy support

func (*HTTP2Transport) Close

func (t *HTTP2Transport) Close()

Close shuts down the transport

func (*HTTP2Transport) Connect added in v1.0.11

func (t *HTTP2Transport) Connect(ctx context.Context, host, port string) error

Connect establishes a connection to the host without making a request. This is used for protocol racing - the first protocol to connect wins.

func (*HTTP2Transport) GetConnectionUseCount

func (t *HTTP2Transport) GetConnectionUseCount(host, port string) int64

GetConnectionUseCount returns how many times a connection has been used

func (*HTTP2Transport) GetDNSCache

func (t *HTTP2Transport) GetDNSCache() *dns.Cache

GetDNSCache returns the DNS cache

func (*HTTP2Transport) GetSessionCache added in v1.5.5

func (t *HTTP2Transport) GetSessionCache() utls.ClientSessionCache

GetSessionCache returns the TLS session cache

func (*HTTP2Transport) IsConnectionReused

func (t *HTTP2Transport) IsConnectionReused(host, port string) bool

IsConnectionReused checks if the connection for a host will be reused Returns true if a usable connection already exists in the pool

func (*HTTP2Transport) RoundTrip

func (t *HTTP2Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper

func (*HTTP2Transport) SetConnectTo added in v1.5.2

func (t *HTTP2Transport) SetConnectTo(requestHost, connectHost string)

SetConnectTo sets a host mapping for domain fronting

func (*HTTP2Transport) SetECHConfig added in v1.5.3

func (t *HTTP2Transport) SetECHConfig(echConfig []byte)

SetECHConfig sets a custom ECH configuration

func (*HTTP2Transport) SetECHConfigDomain added in v1.5.3

func (t *HTTP2Transport) SetECHConfigDomain(domain string)

SetECHConfigDomain sets a domain to fetch ECH config from

func (*HTTP2Transport) SetInsecureSkipVerify added in v1.5.8

func (t *HTTP2Transport) SetInsecureSkipVerify(skip bool)

SetInsecureSkipVerify sets whether to skip TLS certificate verification

func (*HTTP2Transport) SetSessionCache added in v1.5.5

func (t *HTTP2Transport) SetSessionCache(cache utls.ClientSessionCache)

SetSessionCache sets the TLS session cache

func (*HTTP2Transport) Stats

func (t *HTTP2Transport) Stats() map[string]ConnStats

Stats returns transport statistics

type HTTP3Stats

type HTTP3Stats struct {
	RequestCount int64
	DialCount    int64 // Number of new connections created
	Reusing      bool  // True if connections are being reused
}

HTTP3Stats contains HTTP/3 transport statistics

type HTTP3Transport

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

HTTP3Transport is an HTTP/3 transport with proper QUIC connection reuse http3.Transport handles connection pooling internally - we just provide DNS resolution

func NewHTTP3Transport

func NewHTTP3Transport(preset *fingerprint.Preset, dnsCache *dns.Cache) *HTTP3Transport

NewHTTP3Transport creates a new HTTP/3 transport

func NewHTTP3TransportWithConfig added in v1.5.2

func NewHTTP3TransportWithConfig(preset *fingerprint.Preset, dnsCache *dns.Cache, proxyConfig *ProxyConfig, config *TransportConfig) (*HTTP3Transport, error)

NewHTTP3TransportWithConfig creates a new HTTP/3 transport with SOCKS5 proxy and advanced config

func NewHTTP3TransportWithMASQUE added in v1.5.2

func NewHTTP3TransportWithMASQUE(preset *fingerprint.Preset, dnsCache *dns.Cache, proxyConfig *ProxyConfig, config *TransportConfig) (*HTTP3Transport, error)

NewHTTP3TransportWithMASQUE creates a new HTTP/3 transport with MASQUE proxy support. MASQUE allows HTTP/3 (QUIC) traffic to be tunneled through an HTTP/3 proxy using the CONNECT-UDP method defined in RFC 9298.

func NewHTTP3TransportWithProxy added in v1.5.2

func NewHTTP3TransportWithProxy(preset *fingerprint.Preset, dnsCache *dns.Cache, proxyConfig *ProxyConfig) (*HTTP3Transport, error)

NewHTTP3TransportWithProxy creates a new HTTP/3 transport with SOCKS5 proxy support Only SOCKS5 proxies support UDP relay needed for QUIC/HTTP3

func NewHTTP3TransportWithTransportConfig added in v1.5.2

func NewHTTP3TransportWithTransportConfig(preset *fingerprint.Preset, dnsCache *dns.Cache, config *TransportConfig) *HTTP3Transport

NewHTTP3TransportWithTransportConfig creates a new HTTP/3 transport with advanced config

func (*HTTP3Transport) Close

func (t *HTTP3Transport) Close() error

Close shuts down the transport and all connections

func (*HTTP3Transport) Connect added in v1.0.11

func (t *HTTP3Transport) Connect(ctx context.Context, host, port string) error

Connect establishes a QUIC connection to the host without making a request. This is used for protocol racing - the first protocol to connect wins.

func (*HTTP3Transport) GetDNSCache

func (t *HTTP3Transport) GetDNSCache() *dns.Cache

GetDNSCache returns the DNS cache

func (*HTTP3Transport) GetDialCount

func (t *HTTP3Transport) GetDialCount() int64

GetDialCount returns the number of new connections created

func (*HTTP3Transport) GetECHConfigCache added in v1.5.6

func (t *HTTP3Transport) GetECHConfigCache() map[string][]byte

GetECHConfigCache returns all cached ECH configs This is used for session persistence - ECH configs must be saved alongside TLS session tickets to ensure proper session resumption

func (*HTTP3Transport) GetRequestCount

func (t *HTTP3Transport) GetRequestCount() int64

GetRequestCount returns the total number of requests made

func (*HTTP3Transport) GetSessionCache added in v1.5.5

func (t *HTTP3Transport) GetSessionCache() tls.ClientSessionCache

GetSessionCache returns the TLS session cache

func (*HTTP3Transport) IsConnectionReused

func (t *HTTP3Transport) IsConnectionReused(host string) bool

IsConnectionReused returns true if requests > dials (meaning reuse happened)

func (*HTTP3Transport) RoundTrip

func (t *HTTP3Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper

func (*HTTP3Transport) SetConnectTo added in v1.5.2

func (t *HTTP3Transport) SetConnectTo(requestHost, connectHost string)

SetConnectTo sets a host mapping for domain fronting

func (*HTTP3Transport) SetECHConfig added in v1.5.2

func (t *HTTP3Transport) SetECHConfig(echConfig []byte)

SetECHConfig sets a custom ECH configuration

func (*HTTP3Transport) SetECHConfigCache added in v1.5.6

func (t *HTTP3Transport) SetECHConfigCache(configs map[string][]byte)

SetECHConfigCache imports ECH configs from session persistence This should be called before importing TLS sessions to ensure the correct ECH config is used when resuming connections

func (*HTTP3Transport) SetECHConfigDomain added in v1.5.2

func (t *HTTP3Transport) SetECHConfigDomain(domain string)

SetECHConfigDomain sets a domain to fetch ECH config from

func (*HTTP3Transport) SetInsecureSkipVerify added in v1.5.8

func (t *HTTP3Transport) SetInsecureSkipVerify(skip bool)

SetInsecureSkipVerify sets whether to skip TLS certificate verification

func (*HTTP3Transport) SetSessionCache added in v1.5.5

func (t *HTTP3Transport) SetSessionCache(cache tls.ClientSessionCache)

SetSessionCache sets the TLS session cache

func (*HTTP3Transport) Stats

func (t *HTTP3Transport) Stats() HTTP3Stats

Stats returns transport statistics

type HTTPError

type HTTPError struct {
	StatusCode int
	Status     string
	Body       []byte
	Headers    map[string]string
}

HTTPError represents an HTTP-level error (4xx, 5xx responses)

func NewHTTPError

func NewHTTPError(statusCode int, status string, body []byte, headers map[string]string) *HTTPError

NewHTTPError creates an HTTP error from status code

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface

func (*HTTPError) IsClientError

func (e *HTTPError) IsClientError() bool

IsClientError returns true for 4xx errors

func (*HTTPError) IsRetryable

func (e *HTTPError) IsRetryable() bool

IsRetryable returns true for errors that should be retried

func (*HTTPError) IsServerError

func (e *HTTPError) IsServerError() bool

IsServerError returns true for 5xx errors

type PersistableSessionCache added in v1.5.5

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

PersistableSessionCache implements tls.ClientSessionCache with export/import capabilities for session persistence and LRU eviction. Optionally supports a distributed backend for cross-instance session sharing.

func NewPersistableSessionCache added in v1.5.5

func NewPersistableSessionCache() *PersistableSessionCache

NewPersistableSessionCache creates a new persistable session cache

func NewPersistableSessionCacheWithBackend added in v1.5.8

func NewPersistableSessionCacheWithBackend(backend SessionCacheBackend, preset, protocol string, errorCallback ErrorCallback) *PersistableSessionCache

NewPersistableSessionCacheWithBackend creates a session cache with a distributed backend. The preset and protocol are used to generate cache keys for the backend. Protocol should be one of: "h1", "h2", "h3" The errorCallback is optional and will be called when backend operations fail.

func (*PersistableSessionCache) Clear added in v1.5.5

func (c *PersistableSessionCache) Clear()

Clear removes all cached sessions

func (*PersistableSessionCache) Count added in v1.5.5

func (c *PersistableSessionCache) Count() int

Count returns the number of cached sessions

func (*PersistableSessionCache) Export added in v1.5.5

Export serializes all TLS sessions for persistence Returns a map of session keys to serialized TLS session state

func (*PersistableSessionCache) Get added in v1.5.5

func (c *PersistableSessionCache) Get(sessionKey string) (*tls.ClientSessionState, bool)

Get implements tls.ClientSessionCache. If a backend is configured, it will also check the backend on local cache miss.

func (*PersistableSessionCache) GetSessionIdentifier added in v1.5.8

func (c *PersistableSessionCache) GetSessionIdentifier() string

GetSessionIdentifier returns the current session identifier.

func (*PersistableSessionCache) Import added in v1.5.5

func (c *PersistableSessionCache) Import(sessions map[string]TLSSessionState) error

Import loads TLS sessions from serialized state Sessions older than TLSSessionMaxAge are skipped

func (*PersistableSessionCache) Put added in v1.5.5

func (c *PersistableSessionCache) Put(sessionKey string, cs *tls.ClientSessionState)

Put implements tls.ClientSessionCache. If a backend is configured, it will also store the session in the backend.

func (*PersistableSessionCache) SetBackend added in v1.5.8

func (c *PersistableSessionCache) SetBackend(backend SessionCacheBackend, preset, protocol string, errorCallback ErrorCallback)

SetBackend configures a distributed cache backend for this session cache. This allows setting the backend after construction.

func (*PersistableSessionCache) SetErrorCallback added in v1.5.8

func (c *PersistableSessionCache) SetErrorCallback(callback ErrorCallback)

SetErrorCallback sets the callback for backend errors.

func (*PersistableSessionCache) SetSessionIdentifier added in v1.5.8

func (c *PersistableSessionCache) SetSessionIdentifier(sessionId string)

SetSessionIdentifier sets an optional session identifier for cache key isolation. When set, cache keys will include this identifier to prevent TLS session sharing across different proxy configurations (e.g., when using different upstream proxies). This is useful in distributed scenarios where different "sessions" should have isolated TLS session caches even when targeting the same host.

type Protocol

type Protocol int

Protocol represents the HTTP protocol version

const (
	// ProtocolAuto automatically selects the best protocol (H3 -> H2 -> H1)
	ProtocolAuto Protocol = iota
	// ProtocolHTTP1 forces HTTP/1.1 over TCP
	ProtocolHTTP1
	// ProtocolHTTP2 forces HTTP/2 over TCP
	ProtocolHTTP2
	// ProtocolHTTP3 forces HTTP/3 over QUIC
	ProtocolHTTP3
)

func (Protocol) String

func (p Protocol) String() string

String returns the string representation of the protocol

type ProxyConfig

type ProxyConfig struct {
	URL      string // Proxy URL (e.g., "http://proxy:8080" or "http://user:pass@proxy:8080")
	Username string // Proxy username (optional, can also be in URL)
	Password string // Proxy password (optional, can also be in URL)

	// TCPProxy is the proxy URL for TCP-based protocols (HTTP/1.1 and HTTP/2)
	// When set, overrides URL for TCP transports
	TCPProxy string

	// UDPProxy is the proxy URL for UDP-based protocols (HTTP/3 via MASQUE)
	// When set, overrides URL for UDP transports
	UDPProxy string
}

ProxyConfig contains proxy server configuration

type RedirectInfo added in v1.5.1

type RedirectInfo struct {
	StatusCode int
	URL        string
	Headers    map[string][]string // Multi-value headers
}

RedirectInfo contains information about a redirect response

type Request

type Request struct {
	Method     string
	URL        string
	Headers    map[string][]string // Multi-value headers (matches http.Header)
	Body       []byte
	BodyReader io.Reader // For streaming uploads - used instead of Body if set
	Timeout    time.Duration
}

Request represents an HTTP request

type Response

type Response struct {
	StatusCode int
	Headers    map[string][]string // Multi-value headers (matches http.Header)
	Body       io.ReadCloser       // Streaming body - call Close() when done
	FinalURL   string
	Timing     *protocol.Timing
	Protocol   string // "h1", "h2", or "h3"
	History    []*RedirectInfo
	// contains filtered or unexported fields
}

Response represents an HTTP response

func (*Response) Bytes added in v1.5.3

func (r *Response) Bytes() ([]byte, error)

Bytes returns the response body as a byte slice. If the body has already been read, returns the cached bytes. Otherwise reads the body and caches it.

func (*Response) Close added in v1.5.3

func (r *Response) Close() error

Close closes the response body. Should be called when done reading the body.

func (*Response) GetHeader added in v1.5.3

func (r *Response) GetHeader(key string) string

GetHeader returns the first value for the given header key (case-insensitive). Use GetHeaders() for multi-value headers like Set-Cookie.

func (*Response) GetHeaders added in v1.5.3

func (r *Response) GetHeaders(key string) []string

GetHeaders returns all values for the given header key (case-insensitive).

func (*Response) Text added in v1.5.3

func (r *Response) Text() (string, error)

Text returns the response body as a string.

type SessionCacheBackend added in v1.5.8

type SessionCacheBackend interface {
	// Get retrieves a TLS session for the given key.
	// Returns nil, nil if not found.
	// Returns nil, error if backend error (will be propagated to caller).
	Get(ctx context.Context, key string) (*TLSSessionState, error)

	// Put stores a TLS session with the given TTL.
	// TTL should typically be ~24 hours (TLS session ticket lifetime).
	// Returns error if backend error (will be propagated to caller).
	Put(ctx context.Context, key string, session *TLSSessionState, ttl time.Duration) error

	// Delete removes a session from the cache.
	// Returns error if backend error.
	Delete(ctx context.Context, key string) error

	// GetECHConfig retrieves ECH config for a host (required for HTTP/3).
	// Returns nil, nil if not found.
	GetECHConfig(ctx context.Context, key string) ([]byte, error)

	// PutECHConfig stores ECH config for a host.
	PutECHConfig(ctx context.Context, key string, config []byte, ttl time.Duration) error
}

SessionCacheBackend is the interface for distributed TLS session storage. Implementations can use Redis, Memcached, or any other distributed cache. All methods should be safe for concurrent use.

type StreamResponse added in v1.5.3

type StreamResponse struct {
	StatusCode int
	Headers    map[string][]string // Multi-value headers
	FinalURL   string
	Timing     *protocol.Timing
	Protocol   string // "h1", "h2", or "h3"

	// ContentLength is the expected total size (-1 if unknown/chunked)
	ContentLength int64
	// contains filtered or unexported fields
}

StreamResponse represents a streaming HTTP response where the body is read incrementally rather than all at once.

func (*StreamResponse) Close added in v1.5.3

func (r *StreamResponse) Close() error

Close closes the response body and cancels the context

func (*StreamResponse) IsSuccess added in v1.5.3

func (r *StreamResponse) IsSuccess() bool

IsSuccess returns true if the status code is 2xx

func (*StreamResponse) Lines added in v1.5.3

func (r *StreamResponse) Lines() <-chan string

Lines returns a channel that yields lines from the response Close the response when done to stop iteration

func (*StreamResponse) Read added in v1.5.3

func (r *StreamResponse) Read(p []byte) (n int, err error)

Read reads data from the response body

func (*StreamResponse) ReadAll added in v1.5.3

func (r *StreamResponse) ReadAll() ([]byte, error)

ReadAll reads the entire response body into memory This defeats the purpose of streaming but is useful for small responses

func (*StreamResponse) ReadChunk added in v1.5.3

func (r *StreamResponse) ReadChunk(size int) ([]byte, error)

ReadChunk reads up to size bytes from the response

func (*StreamResponse) Scanner added in v1.5.3

func (r *StreamResponse) Scanner() *bufio.Scanner

Scanner returns a bufio.Scanner for line-by-line reading

type TLSSessionState added in v1.5.5

type TLSSessionState struct {
	Ticket    string    `json:"ticket"` // base64 encoded
	State     string    `json:"state"`  // base64 encoded
	CreatedAt time.Time `json:"created_at"`
}

TLSSessionState represents a serializable TLS session

func NewTLSSessionState added in v1.5.8

func NewTLSSessionState(cs *tls.ClientSessionState) (*TLSSessionState, error)

NewTLSSessionState creates a TLSSessionState from a ClientSessionState.

func (*TLSSessionState) ToClientSessionState added in v1.5.8

func (s *TLSSessionState) ToClientSessionState() (*tls.ClientSessionState, error)

ToClientSessionState converts a serialized TLS session back to a ClientSessionState.

type Transport

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

Transport is a unified HTTP transport supporting HTTP/1.1, HTTP/2, and HTTP/3

func NewTransport

func NewTransport(presetName string) *Transport

NewTransport creates a new unified transport

func NewTransportWithConfig added in v1.5.2

func NewTransportWithConfig(presetName string, proxy *ProxyConfig, config *TransportConfig) *Transport

NewTransportWithConfig creates a new unified transport with proxy and config

func NewTransportWithProxy

func NewTransportWithProxy(presetName string, proxy *ProxyConfig) *Transport

NewTransportWithProxy creates a new unified transport with optional proxy

func (*Transport) ClearProtocolCache

func (t *Transport) ClearProtocolCache()

ClearProtocolCache clears the learned protocol support cache

func (*Transport) Close

func (t *Transport) Close()

Close shuts down the transport

func (*Transport) Do

func (t *Transport) Do(ctx context.Context, req *Request) (*Response, error)

Do executes an HTTP request

func (*Transport) DoStream added in v1.5.3

func (t *Transport) DoStream(ctx context.Context, req *Request) (*StreamResponse, error)

DoStream executes an HTTP request and returns a streaming response The caller is responsible for closing the response when done

func (*Transport) GetDNSCache

func (t *Transport) GetDNSCache() *dns.Cache

GetDNSCache returns the DNS cache

func (*Transport) GetHTTP1Transport added in v1.5.5

func (t *Transport) GetHTTP1Transport() *HTTP1Transport

GetHTTP1Transport returns the HTTP/1.1 transport for TLS session cache access

func (*Transport) GetHTTP2Transport added in v1.5.5

func (t *Transport) GetHTTP2Transport() *HTTP2Transport

GetHTTP2Transport returns the HTTP/2 transport for TLS session cache access

func (*Transport) GetHTTP3Transport added in v1.5.5

func (t *Transport) GetHTTP3Transport() *HTTP3Transport

GetHTTP3Transport returns the HTTP/3 transport for TLS session cache access

func (*Transport) GetHeaderOrder added in v1.5.8

func (t *Transport) GetHeaderOrder() []string

GetHeaderOrder returns the current header order. Returns preset's default order if no custom order is set.

func (*Transport) SetConnectTo added in v1.5.2

func (t *Transport) SetConnectTo(requestHost, connectHost string)

SetConnectTo sets a host mapping for domain fronting

func (*Transport) SetECHConfig added in v1.5.2

func (t *Transport) SetECHConfig(echConfig []byte)

SetECHConfig sets a custom ECH configuration

func (*Transport) SetECHConfigDomain added in v1.5.2

func (t *Transport) SetECHConfigDomain(domain string)

SetECHConfigDomain sets a domain to fetch ECH config from

func (*Transport) SetHeaderOrder added in v1.5.8

func (t *Transport) SetHeaderOrder(order []string)

SetHeaderOrder sets a custom header order for all requests. Pass nil or empty slice to reset to preset's default order. Order should contain lowercase header names.

func (*Transport) SetInsecureSkipVerify

func (t *Transport) SetInsecureSkipVerify(skip bool)

SetInsecureSkipVerify sets whether to skip TLS certificate verification

func (*Transport) SetPreset

func (t *Transport) SetPreset(presetName string)

SetPreset changes the fingerprint preset

func (*Transport) SetProtocol

func (t *Transport) SetProtocol(p Protocol)

SetProtocol sets the preferred protocol

func (*Transport) SetProxy

func (t *Transport) SetProxy(proxy *ProxyConfig)

SetProxy sets or updates the proxy configuration Note: This recreates the underlying transports

func (*Transport) SetSessionIdentifier added in v1.5.8

func (t *Transport) SetSessionIdentifier(sessionId string)

SetSessionIdentifier sets a session identifier on all TLS session caches. This is used to isolate TLS sessions when the same host is accessed through different proxies or with different session configurations. The identifier is included in distributed cache keys to prevent session sharing.

func (*Transport) SetTimeout

func (t *Transport) SetTimeout(timeout time.Duration)

SetTimeout sets the request timeout

func (*Transport) Stats

func (t *Transport) Stats() map[string]interface{}

Stats returns transport statistics

type TransportConfig added in v1.5.2

type TransportConfig struct {
	// ConnectTo maps request hosts to connection hosts (domain fronting).
	// Key: request host, Value: connection host for DNS resolution
	ConnectTo map[string]string

	// ECHConfig is a custom ECH configuration (overrides DNS fetch)
	ECHConfig []byte

	// ECHConfigDomain is a domain to fetch ECH config from instead of target
	ECHConfigDomain string

	// TLSOnly mode: use TLS fingerprint but skip preset HTTP headers
	// User sets all headers manually
	TLSOnly bool

	// QuicIdleTimeout is the idle timeout for QUIC connections (default: 30s)
	QuicIdleTimeout time.Duration

	// SessionCacheBackend is an optional distributed cache for TLS sessions.
	// When set, TLS session tickets will be stored/retrieved from this backend,
	// enabling session sharing across multiple instances.
	SessionCacheBackend SessionCacheBackend

	// SessionCacheErrorCallback is called when backend operations fail.
	// This is optional but recommended for monitoring backend health.
	SessionCacheErrorCallback ErrorCallback
}

TransportConfig contains advanced transport configuration

func (*TransportConfig) GetConnectHost added in v1.5.2

func (c *TransportConfig) GetConnectHost(requestHost string) string

GetConnectHost returns the connection host for a request host. If there's a ConnectTo mapping, returns the mapped host. Otherwise returns the original host.

func (*TransportConfig) GetECHConfig added in v1.5.2

func (c *TransportConfig) GetECHConfig(ctx context.Context, targetHost string) []byte

GetECHConfig returns the ECH config to use for a host. Returns custom config if set, otherwise fetches from ECHConfigDomain or target host.

type TransportError

type TransportError struct {
	Op        string // Operation that failed (e.g., "dial", "tls_handshake", "request")
	Host      string // Target host
	Port      string // Target port
	Protocol  string // Protocol (h1, h2, h3)
	Cause     error  // Underlying error
	Category  error  // Error category (ErrConnection, ErrTLS, etc.)
	Retryable bool   // Whether the operation can be retried
}

TransportError provides detailed error information

func NewConnectionError

func NewConnectionError(op, host, port, protocol string, cause error) *TransportError

NewConnectionError creates a connection error

func NewDNSError

func NewDNSError(host string, cause error) *TransportError

NewDNSError creates a DNS error

func NewProtocolError

func NewProtocolError(host, port, protocol string, cause error) *TransportError

NewProtocolError creates a protocol negotiation error

func NewProxyError

func NewProxyError(op, host, port string, cause error) *TransportError

NewProxyError creates a proxy error

func NewRequestError

func NewRequestError(op, host, port, protocol string, cause error) *TransportError

NewRequestError creates a request error

func NewTLSError

func NewTLSError(op, host, port, protocol string, cause error) *TransportError

NewTLSError creates a TLS error

func NewTimeoutError

func NewTimeoutError(op, host, port, protocol string, cause error) *TransportError

NewTimeoutError creates a timeout error

func (*TransportError) Error

func (e *TransportError) Error() string

Error implements the error interface

func (*TransportError) Is

func (e *TransportError) Is(target error) bool

Is checks if the error matches the target

func (*TransportError) IsRetryable

func (e *TransportError) IsRetryable() bool

IsRetryable returns whether the error is retryable

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Unwrap returns the underlying error

Jump to

Keyboard shortcuts

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