Documentation
¶
Overview ¶
Package httpcloak provides an HTTP client with perfect browser TLS/HTTP fingerprinting.
httpcloak allows you to make HTTP requests that are indistinguishable from real browsers, bypassing TLS fingerprinting, HTTP/2 fingerprinting, and header-based bot detection.
Basic usage:
client := httpcloak.New("chrome-146")
defer client.Close()
resp, err := client.Get(ctx, "https://example.com")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(resp.Body))
With options:
client := httpcloak.New("chrome-146",
httpcloak.WithTimeout(30*time.Second),
httpcloak.WithProxy("http://user:pass@proxy:8080"),
)
Index ¶
- Constants
- func BuildMultipart(fields []MultipartField) ([]byte, string, error)
- func Presets() []string
- func SetKeyLogWriter(w io.Writer)
- func ValidateSessionFile(path string) error
- type Client
- func (c *Client) Close()
- func (c *Client) Do(ctx context.Context, req *Request) (*Response, error)
- func (c *Client) Get(ctx context.Context, url string) (*Response, error)
- func (c *Client) GetWithHeaders(ctx context.Context, url string, headers map[string][]string) (*Response, error)
- func (c *Client) Post(ctx context.Context, url string, body io.Reader, contentType string) (*Response, error)
- func (c *Client) PostForm(ctx context.Context, url string, body []byte) (*Response, error)
- func (c *Client) PostJSON(ctx context.Context, url string, body []byte) (*Response, error)
- func (c *Client) PostMultipart(ctx context.Context, url string, fields []MultipartField) (*Response, error)
- type CookieInfo
- type CustomFingerprint
- type LocalProxy
- func (p *LocalProxy) GetSession(sessionID string) *Session
- func (p *LocalProxy) IsRunning() bool
- func (p *LocalProxy) ListSessions() []string
- func (p *LocalProxy) Port() int
- func (p *LocalProxy) RegisterSession(sessionID string, session *Session) error
- func (p *LocalProxy) Stats() map[string]interface{}
- func (p *LocalProxy) Stop() error
- func (p *LocalProxy) UnregisterSession(sessionID string) *Session
- type LocalProxyConfig
- type LocalProxyOption
- func WithProxyMaxConnections(n int) LocalProxyOption
- func WithProxyPreset(preset string) LocalProxyOption
- func WithProxySessionCache(backend transport.SessionCacheBackend, errorCallback transport.ErrorCallback) LocalProxyOption
- func WithProxyTLSOnly() LocalProxyOption
- func WithProxyTimeout(d time.Duration) LocalProxyOption
- func WithProxyUpstream(tcpProxy, udpProxy string) LocalProxyOption
- type Manager
- type MultipartField
- type Option
- type RedirectInfo
- type Request
- type Response
- type Session
- func (s *Session) ClearCache()
- func (s *Session) ClearCookies()
- func (s *Session) Close()
- func (s *Session) ConditionalCacheEnabled() bool
- func (s *Session) DeleteCookie(name, domain string)
- func (s *Session) Do(ctx context.Context, req *Request) (*Response, error)
- func (s *Session) DoStream(ctx context.Context, req *Request) (*StreamResponse, error)
- func (s *Session) DoWithBody(ctx context.Context, req *Request, bodyReader io.Reader) (*Response, error)
- func (s *Session) FollowRedirects() bool
- func (s *Session) Fork(n int) []*Session
- func (s *Session) Get(ctx context.Context, url string) (*Response, error)
- func (s *Session) GetCookies() []CookieInfo
- func (s *Session) GetCookiesDetailed() []CookieInfo
- func (s *Session) GetHeaderOrder() []string
- func (s *Session) GetProxy() string
- func (s *Session) GetStream(ctx context.Context, url string) (*StreamResponse, error)
- func (s *Session) GetStreamWithHeaders(ctx context.Context, url string, headers map[string][]string) (*StreamResponse, error)
- func (s *Session) GetTCPProxy() string
- func (s *Session) GetTransport() *transport.Transport
- func (s *Session) GetUDPProxy() string
- func (s *Session) IdleTime() time.Duration
- func (s *Session) IsActive() bool
- func (s *Session) Marshal() ([]byte, error)
- func (s *Session) MaxRedirects() int
- func (s *Session) Refresh()
- func (s *Session) RefreshWithProtocol(protocol string) error
- func (s *Session) Save(path string) error
- func (s *Session) SetConditionalCacheEnabled(enabled bool)
- func (s *Session) SetCookie(cookie CookieInfo)
- func (s *Session) SetFollowRedirects(enabled bool)
- func (s *Session) SetHeaderOrder(order []string)
- func (s *Session) SetMaxRedirects(max int)
- func (s *Session) SetProxy(proxyURL string)
- func (s *Session) SetSessionIdentifier(sessionId string)
- func (s *Session) SetTCPProxy(proxyURL string)
- func (s *Session) SetUDPProxy(proxyURL string)
- func (s *Session) Stats() session.SessionStats
- func (s *Session) Touch()
- func (s *Session) Warmup(ctx context.Context, url string) error
- type SessionOption
- func WithConnectTo(requestHost, connectHost string) SessionOption
- func WithCustomFingerprint(fp CustomFingerprint) SessionOption
- func WithDisableECH() SessionOption
- func WithDisableHTTP3() SessionOption
- func WithECHFrom(domain string) SessionOption
- func WithEnableSpeculativeTLS() SessionOption
- func WithForceHTTP1() SessionOption
- func WithForceHTTP2() SessionOption
- func WithForceHTTP3() SessionOption
- func WithInsecureSkipVerify() SessionOption
- func WithKeyLogFile(path string) SessionOption
- func WithLocalAddrIP(ip net.IP) SessionOption
- func WithLocalAddress(addr string) SessionOption
- func WithQuicIdleTimeout(d time.Duration) SessionOption
- func WithRedirects(follow bool, maxRedirects int) SessionOption
- func WithRetry(count int) SessionOption
- func WithRetryConfig(count int, waitMin, waitMax time.Duration, retryOnStatus []int) SessionOption
- func WithSessionCache(backend transport.SessionCacheBackend, errorCallback transport.ErrorCallback) SessionOption
- func WithSessionPreferIPv4() SessionOption
- func WithSessionProxy(proxyURL string) SessionOption
- func WithSessionTCPProxy(proxyURL string) SessionOption
- func WithSessionTimeout(d time.Duration) SessionOption
- func WithSessionUDPProxy(proxyURL string) SessionOption
- func WithSwitchProtocol(protocol string) SessionOption
- func WithTCPFingerprint(fp fingerprint.TCPFingerprint) SessionOption
- func WithTLSOnly() SessionOption
- func WithoutConditionalCache() SessionOption
- func WithoutCookieJar() SessionOption
- func WithoutRedirects() SessionOption
- func WithoutRetry() SessionOption
- type StreamResponse
Constants ¶
const ( // HeaderUpstreamProxy is the header name for per-request proxy override (HTTP only). // For HTTPS/CONNECT requests, use Proxy-Authorization header instead. HeaderUpstreamProxy = "X-Upstream-Proxy" // HeaderTLSOnly is the header name for per-request TLS-only mode override. // When set to "true", TLS fingerprinting is applied but preset HTTP headers are skipped. // When set to "false", normal mode is used (preset headers applied). // If not set, uses the proxy's global TLSOnly setting. HeaderTLSOnly = "X-HTTPCloak-TlsOnly" // HeaderSession is the header name for per-request session selection. // When set, the proxy uses the specified session ID to route the request. // Sessions must be registered via RegisterSession() before use. // Example: X-HTTPCloak-Session: my-session-id HeaderSession = "X-HTTPCloak-Session" // HeaderScheme upgrades HTTP requests to HTTPS with TLS fingerprinting. // When set to "https", LocalProxy converts http:// URLs to https:// and uses // Session.DoStream() with full fingerprinting. This allows standard HTTP proxy // clients to get HTTPS fingerprinting without using CONNECT tunneling. // Example: X-HTTPCloak-Scheme: https HeaderScheme = "X-HTTPCloak-Scheme" // ProxyAuthScheme is the authentication scheme for upstream proxy selection. // Format: "Proxy-Authorization: HTTPCloak http://user:pass@proxy:8080" // This works for both HTTP and HTTPS (CONNECT) requests since Proxy-Authorization // is sent with CONNECT requests by standard HTTP clients. ProxyAuthScheme = "HTTPCloak" )
Variables ¶
This section is empty.
Functions ¶
func BuildMultipart ¶ added in v1.6.1
func BuildMultipart(fields []MultipartField) ([]byte, string, error)
BuildMultipart encodes fields into a multipart/form-data body. Returns the encoded body bytes and the Content-Type header value (including boundary).
func SetKeyLogWriter ¶ added in v1.6.7
SetKeyLogWriter installs a process-global writer that the lib uses to emit TLS keylog lines (NSS keylog format). Pass nil to disable.
This is the io.Writer-flavoured sibling of WithSessionKeyLogFile, which takes a file path. Use SetKeyLogWriter when the destination is something other than a file: a ring buffer, an S3 multipart uploader, a syslog pipe, etc. Setting a writer affects every TLS handshake the binary performs from the moment it's set.
func ValidateSessionFile ¶ added in v1.6.7
ValidateSessionFile validates a session file without loading it. Returns nil if the file at path is a valid httpcloak session blob, or a descriptive error otherwise. Useful for pre-flight checks before LoadSession on user-supplied paths.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client with browser fingerprint spoofing
func New ¶
New creates a new HTTP client with the specified browser fingerprint.
Available presets:
- "chrome-latest" (recommended), "chrome-latest-windows", "chrome-latest-linux", "chrome-latest-macos"
- "chrome-146", "chrome-145", "chrome-144", "chrome-143", "chrome-141", "chrome-133"
- "firefox-latest", "firefox-133"
- "safari-latest", "safari-18"
- "chrome-latest-ios", "safari-latest-ios"
- "chrome-latest-android"
The -latest aliases always resolve to the newest version in the library.
Example:
client := httpcloak.New("chrome-latest")
defer client.Close()
func (*Client) GetWithHeaders ¶
func (c *Client) GetWithHeaders(ctx context.Context, url string, headers map[string][]string) (*Response, error)
GetWithHeaders performs a GET request with custom headers
func (*Client) Post ¶
func (c *Client) Post(ctx context.Context, url string, body io.Reader, contentType string) (*Response, error)
Post performs a POST request
func (*Client) PostMultipart ¶ added in v1.6.1
func (c *Client) PostMultipart(ctx context.Context, url string, fields []MultipartField) (*Response, error)
PostMultipart performs a POST request with multipart/form-data body.
type CookieInfo ¶ added in v1.6.1
type CookieInfo = session.CookieState
CookieInfo represents a cookie with full metadata (domain, path, expiry, etc.)
type CustomFingerprint ¶ added in v1.6.1
type CustomFingerprint struct {
// JA3 is a JA3 fingerprint string.
// Format: TLSVersion,CipherSuites,Extensions,EllipticCurves,PointFormats
// Example: "771,4865-4866-4867-49195-49199,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513-21,29-23-24,0"
JA3 string
// Akamai is an Akamai HTTP/2 fingerprint string.
// Format: SETTINGS|WINDOW_UPDATE|PRIORITY|PSEUDO_HEADER_ORDER
// Example: "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p"
Akamai string
// SignatureAlgorithms overrides the default signature algorithms for the JA3 spec.
// Valid values: "ecdsa_secp256r1_sha256", "rsa_pss_rsae_sha256", "rsa_pkcs1_sha256",
// "ecdsa_secp384r1_sha384", "rsa_pss_rsae_sha384", "rsa_pkcs1_sha384",
// "rsa_pss_rsae_sha512", "rsa_pkcs1_sha512"
SignatureAlgorithms []string
// ALPN overrides the default ALPN protocols. Default: ["h2", "http/1.1"]
ALPN []string
// CertCompression overrides the cert compression algorithms.
// Valid values: "brotli", "zlib", "zstd"
CertCompression []string
// PermuteExtensions randomly permutes the TLS extension order.
PermuteExtensions bool
}
CustomFingerprint configures custom TLS (JA3) and HTTP/2 (Akamai) fingerprints. This overrides the preset's fingerprint for fine-grained control.
type LocalProxy ¶ added in v1.5.8
type LocalProxy struct {
// contains filtered or unexported fields
}
LocalProxy is an HTTP proxy server that forwards requests through httpcloak sessions with TLS fingerprinting.
Architecture: - For HTTP requests: Forwards through httpcloak Session (fingerprinting applied) - For HTTPS (CONNECT): Tunnels TCP (client does TLS, fingerprinting via upstream proxy only)
Usage with C# HttpClient:
proxy := httpcloak.StartLocalProxy(8080, "chrome-146") defer proxy.Stop() // Configure HttpClient to use http://localhost:8080 as proxy
func StartLocalProxy ¶ added in v1.5.8
func StartLocalProxy(port int, opts ...LocalProxyOption) (*LocalProxy, error)
StartLocalProxy creates and starts a local HTTP proxy on the specified port. The proxy forwards requests through httpcloak sessions with TLS fingerprinting.
Example:
proxy, err := httpcloak.StartLocalProxy(8080, httpcloak.WithProxyPreset("chrome-146"))
if err != nil {
log.Fatal(err)
}
defer proxy.Stop()
fmt.Printf("Proxy running on port %d\n", proxy.Port())
func (*LocalProxy) GetSession ¶ added in v1.5.8
func (p *LocalProxy) GetSession(sessionID string) *Session
GetSession returns a registered session by ID. Returns nil if the session is not found.
func (*LocalProxy) IsRunning ¶ added in v1.5.8
func (p *LocalProxy) IsRunning() bool
IsRunning returns whether the proxy is running
func (*LocalProxy) ListSessions ¶ added in v1.5.8
func (p *LocalProxy) ListSessions() []string
ListSessions returns all registered session IDs.
func (*LocalProxy) Port ¶ added in v1.5.8
func (p *LocalProxy) Port() int
Port returns the port the proxy is listening on
func (*LocalProxy) RegisterSession ¶ added in v1.5.8
func (p *LocalProxy) RegisterSession(sessionID string, session *Session) error
RegisterSession registers a session with the given ID for per-request session selection. The session can then be selected via the X-HTTPCloak-Session header. Returns an error if a session with the same ID already exists.
Example:
session := httpcloak.NewSession("chrome-146", httpcloak.WithSessionProxy("..."))
proxy.RegisterSession("session-1", session)
// Client can now use: X-HTTPCloak-Session: session-1
func (*LocalProxy) Stats ¶ added in v1.5.8
func (p *LocalProxy) Stats() map[string]interface{}
Stats returns proxy statistics
func (*LocalProxy) Stop ¶ added in v1.5.8
func (p *LocalProxy) Stop() error
Stop stops the local proxy server gracefully
func (*LocalProxy) UnregisterSession ¶ added in v1.5.8
func (p *LocalProxy) UnregisterSession(sessionID string) *Session
UnregisterSession removes a session from the registry. The session is NOT closed - caller is responsible for closing it. Returns the session if found, nil otherwise.
type LocalProxyConfig ¶ added in v1.5.8
type LocalProxyConfig struct {
// Port to listen on (0 = auto-select)
Port int
// Browser fingerprint preset (default: chrome-146)
Preset string
// Request timeout
Timeout time.Duration
// Maximum concurrent connections
MaxConnections int
// Upstream proxy (optional)
TCPProxy string
UDPProxy string
// TLSOnly mode: only apply TLS fingerprinting, pass HTTP headers through unchanged.
// Useful when the client (e.g., Playwright) already provides authentic browser headers.
TLSOnly bool
// SessionCacheBackend is an optional distributed cache for TLS sessions.
// Enables session sharing across multiple LocalProxy instances.
SessionCacheBackend transport.SessionCacheBackend
// SessionCacheErrorCallback is called when backend operations fail.
SessionCacheErrorCallback transport.ErrorCallback
}
LocalProxyConfig holds configuration for the local proxy
type LocalProxyOption ¶ added in v1.5.8
type LocalProxyOption func(*LocalProxyConfig)
LocalProxyOption configures the local proxy
func WithProxyMaxConnections ¶ added in v1.5.8
func WithProxyMaxConnections(n int) LocalProxyOption
WithProxyMaxConnections sets the maximum concurrent connections
func WithProxyPreset ¶ added in v1.5.8
func WithProxyPreset(preset string) LocalProxyOption
WithProxyPreset sets the browser fingerprint preset
func WithProxySessionCache ¶ added in v1.5.8
func WithProxySessionCache(backend transport.SessionCacheBackend, errorCallback transport.ErrorCallback) LocalProxyOption
WithProxySessionCache sets a distributed TLS session cache backend for the proxy. This enables TLS session ticket sharing across multiple proxy instances.
func WithProxyTLSOnly ¶ added in v1.5.8
func WithProxyTLSOnly() LocalProxyOption
WithProxyTLSOnly enables TLS-only mode where only TLS fingerprinting is applied. HTTP headers from the client pass through unchanged - useful when using Playwright or other browsers that already provide authentic headers.
func WithProxyTimeout ¶ added in v1.5.8
func WithProxyTimeout(d time.Duration) LocalProxyOption
WithProxyTimeout sets the request timeout
func WithProxyUpstream ¶ added in v1.5.8
func WithProxyUpstream(tcpProxy, udpProxy string) LocalProxyOption
WithProxyUpstream sets upstream proxy URLs for the httpcloak session
type Manager ¶ added in v1.6.7
Manager is an in-process registry for many sessions at once. It's the right tool for worker pools, multi-tenant scrapers, or any service that needs to look up sessions by external ID with bounded concurrency and idle eviction. Re-exported from the session subpackage so callers don't have to import it directly. See the connection-lifecycle/session-manager chapter for usage.
func NewManager ¶ added in v1.6.7
func NewManager() *Manager
NewManager constructs a fresh session Manager with the package defaults (max 100 concurrent sessions, 30-minute idle timeout, 1-minute cleanup interval). Override the bounds with Manager.SetMaxSessions and Manager.SetSessionTimeout.
type MultipartField ¶ added in v1.6.1
type MultipartField struct {
Name string // Form field name
Value string // Text value (used when Filename is empty)
Filename string // If set, this field is a file upload
Content []byte // File content (used when Filename is set)
ContentType string // MIME type for file uploads (default: application/octet-stream)
}
MultipartField represents a single field in a multipart/form-data body. For text fields, set Name and Value. For file uploads, set Name, Filename, Content, and optionally ContentType (defaults to application/octet-stream).
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 io.Reader // Streaming body for uploads
Timeout time.Duration
// TLSOnly is a per-request override for TLS-only mode.
// When set to true, preset HTTP headers are NOT applied - only TLS fingerprinting is used.
// When nil, the session's TLSOnly setting is used.
// This is useful for LocalProxy where each request can have different TLS-only settings
// via the X-HTTPCloak-TlsOnly header.
TLSOnly *bool
// FollowRedirects, when non-nil, overrides the session's follow-redirects
// policy for this single request. Set to &true to follow redirects on this
// request, &false to surface the 3xx response back to the caller. When nil,
// the session-level setting is used.
FollowRedirects *bool
// DisableConditionalCache, when true, skips ETag / If-Modified-Since handling
// for this single request: no cache validators are injected on the way out
// and any ETag / Last-Modified on the response is not stored in the session
// cache. Useful for forcing a fresh fetch without touching the session-wide
// setting.
DisableConditionalCache bool
}
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
Protocol string
History []*RedirectInfo
// contains filtered or unexported fields
}
Response represents an HTTP response
func (*Response) Bytes ¶ added in v1.5.3
Bytes reads and returns the entire response body. The body can only be read once unless cached.
func (*Response) GetHeader ¶ added in v1.5.3
GetHeader returns the first value for the given header key.
func (*Response) GetHeaders ¶ added in v1.5.3
GetHeaders returns all values for the given header key.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a persistent HTTP session with cookie management
func LoadSession ¶ added in v1.5.5
LoadSession loads a session from a file
func NewSession ¶
func NewSession(preset string, opts ...SessionOption) *Session
NewSession creates a new persistent session with cookie management
func UnmarshalSession ¶ added in v1.5.5
UnmarshalSession loads a session from JSON bytes
func (*Session) ClearCache ¶ added in v1.6.7
func (s *Session) ClearCache()
ClearCache drops the conditional-request cache (ETag / Last-Modified entries). Cookies and TLS tickets are not affected.
func (*Session) ClearCookies ¶ added in v1.6.1
func (s *Session) ClearCookies()
ClearCookies removes all cookies from the session
func (*Session) ConditionalCacheEnabled ¶ added in v1.6.7
ConditionalCacheEnabled reports whether the session is currently injecting and storing ETag / If-Modified-Since validators.
func (*Session) DeleteCookie ¶ added in v1.6.1
DeleteCookie removes cookies by name. If domain is empty, removes from all domains.
func (*Session) DoStream ¶ added in v1.5.3
DoStream executes an HTTP request and returns a streaming response The caller is responsible for closing the response when done Note: Streaming does NOT support redirects - use Do() for redirect handling
func (*Session) DoWithBody ¶ added in v1.5.3
func (s *Session) DoWithBody(ctx context.Context, req *Request, bodyReader io.Reader) (*Response, error)
DoWithBody executes a request with an io.Reader as the body for streaming uploads
func (*Session) FollowRedirects ¶ added in v1.6.7
FollowRedirects reports the session's current redirect-following policy. Per-request overrides via Request.FollowRedirects don't change this value.
func (*Session) Fork ¶ added in v1.6.0
Fork creates n new sessions that share cookies and TLS session caches with the parent, but have independent connections. This simulates multiple browser tabs — same cookies, same TLS resumption tickets, same fingerprint, but independent TCP/QUIC connections for parallel requests.
func (*Session) GetCookies ¶
func (s *Session) GetCookies() []CookieInfo
GetCookies returns all cookies stored in the session with full metadata.
Note: In bindings (Node.js, Python, .NET), GetCookies currently returns a flat name-value map for backward compatibility, with a deprecation warning. In a future release, all bindings will change to return the same []CookieInfo format as this Go method. GetCookiesDetailed already returns this format in all bindings.
func (*Session) GetCookiesDetailed ¶ added in v1.6.1
func (s *Session) GetCookiesDetailed() []CookieInfo
GetCookiesDetailed returns all cookies with full metadata (domain, path, expiry, etc.)
func (*Session) GetHeaderOrder ¶ added in v1.5.8
GetHeaderOrder returns the current header order. Returns preset's default order if no custom order is set.
func (*Session) GetProxy ¶ added in v1.5.8
GetProxy returns the current proxy URL (unified proxy or TCP proxy)
func (*Session) GetStreamWithHeaders ¶ added in v1.5.3
func (s *Session) GetStreamWithHeaders(ctx context.Context, url string, headers map[string][]string) (*StreamResponse, error)
GetStreamWithHeaders performs a streaming GET request with custom headers
func (*Session) GetTCPProxy ¶ added in v1.5.8
GetTCPProxy returns the current TCP proxy URL
func (*Session) GetTransport ¶ added in v1.6.7
GetTransport returns the underlying transport. Escape hatch for advanced transport-level access; the lib reserves the right to evolve the transport surface between releases.
func (*Session) GetUDPProxy ¶ added in v1.5.8
GetUDPProxy returns the current UDP proxy URL
func (*Session) IdleTime ¶ added in v1.6.7
IdleTime returns time since the session last serviced a request.
func (*Session) IsActive ¶ added in v1.6.7
IsActive reports whether the session is still usable. False once Close has run.
func (*Session) MaxRedirects ¶ added in v1.6.7
MaxRedirects reports the session's current redirect cap.
func (*Session) Refresh ¶ added in v1.5.10
func (s *Session) Refresh()
Refresh closes all connections but keeps TLS session caches and cookies intact. This simulates a browser page refresh - new TCP/QUIC connections but TLS resumption. If a switchProtocol was configured, the session switches to that protocol.
func (*Session) RefreshWithProtocol ¶ added in v1.6.0
RefreshWithProtocol closes all connections and switches to a new protocol. The protocol change persists for future Refresh() calls as well. Valid protocols: "h1", "h2", "h3", "auto".
func (*Session) SetConditionalCacheEnabled ¶ added in v1.6.7
SetConditionalCacheEnabled toggles the session's ETag / If-Modified-Since handling at runtime. When false, the session stops injecting cache validators on outgoing requests and stops storing them from responses. Pair with ClearCache to also wipe any previously-stored validators.
func (*Session) SetCookie ¶
func (s *Session) SetCookie(cookie CookieInfo)
SetCookie sets a cookie in the session with full metadata
func (*Session) SetFollowRedirects ¶ added in v1.6.7
SetFollowRedirects toggles the session's redirect-following policy at runtime. A per-request Request.FollowRedirects override still wins over this value for that one request.
func (*Session) SetHeaderOrder ¶ added in v1.5.8
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 (*Session) SetMaxRedirects ¶ added in v1.6.7
SetMaxRedirects updates the session's redirect cap at runtime. Values of zero or below are ignored, leaving the prior cap (or the default of 10) in place.
func (*Session) SetProxy ¶ added in v1.5.8
SetProxy sets or updates the proxy for all protocols (HTTP/1.1, HTTP/2, HTTP/3) This closes existing connections and recreates transports with the new proxy Pass empty string to switch to direct connection
func (*Session) SetSessionIdentifier ¶ added in v1.5.8
SetSessionIdentifier sets a session identifier for TLS cache key isolation. This is used when the session is registered with a LocalProxy to ensure TLS sessions are isolated per proxy/session configuration in distributed caches.
func (*Session) SetTCPProxy ¶ added in v1.5.8
SetTCPProxy sets the proxy for TCP protocols (HTTP/1.1, HTTP/2)
func (*Session) SetUDPProxy ¶ added in v1.5.8
SetUDPProxy sets the proxy for UDP protocols (HTTP/3 via SOCKS5 or MASQUE)
func (*Session) Stats ¶ added in v1.6.7
func (s *Session) Stats() session.SessionStats
Stats returns a snapshot of session counters and timestamps.
func (*Session) Touch ¶ added in v1.6.7
func (s *Session) Touch()
Touch resets the idle timer to now without issuing a request.
type SessionOption ¶
type SessionOption func(*sessionConfig)
SessionOption configures a session
func WithConnectTo ¶ added in v1.5.2
func WithConnectTo(requestHost, connectHost string) SessionOption
WithConnectTo sets a host mapping for domain fronting. Requests to requestHost will connect to connectHost instead. The TLS SNI and Host header will still use requestHost.
func WithCustomFingerprint ¶ added in v1.6.1
func WithCustomFingerprint(fp CustomFingerprint) SessionOption
func WithDisableECH ¶ added in v1.6.0
func WithDisableECH() SessionOption
WithDisableECH disables ECH (Encrypted Client Hello) lookup for faster first request. ECH is an optional privacy feature that adds ~15-20ms to first connection. Disabling it has no security impact, only privacy implications.
func WithDisableHTTP3 ¶ added in v1.6.5
func WithDisableHTTP3() SessionOption
WithDisableHTTP3 disables HTTP/3 (QUIC) while keeping H1/H2 auto-negotiation. Use this when QUIC is unreliable on your network or when binding to a local address that doesn't support UDP.
func WithECHFrom ¶ added in v1.5.2
func WithECHFrom(domain string) SessionOption
WithECHFrom sets a domain to fetch ECH config from. Instead of fetching ECH from the target domain's DNS, the config will be fetched from this domain. Useful for Cloudflare domains - use "cloudflare-ech.com" to get ECH config that works for any Cloudflare-proxied domain.
func WithEnableSpeculativeTLS ¶ added in v1.6.0
func WithEnableSpeculativeTLS() SessionOption
WithEnableSpeculativeTLS enables the speculative TLS optimization for proxy connections. When enabled, the CONNECT request and TLS ClientHello are sent together, saving one round-trip (~25% faster). Disabled by default due to compatibility issues with some proxies.
func WithForceHTTP1 ¶ added in v1.0.1
func WithForceHTTP1() SessionOption
WithForceHTTP1 forces HTTP/1.1 protocol
func WithForceHTTP2 ¶ added in v1.0.1
func WithForceHTTP2() SessionOption
WithForceHTTP2 forces HTTP/2 protocol
func WithForceHTTP3 ¶ added in v1.1.1
func WithForceHTTP3() SessionOption
WithForceHTTP3 forces HTTP/3 protocol (QUIC)
func WithInsecureSkipVerify ¶ added in v1.0.1
func WithInsecureSkipVerify() SessionOption
WithInsecureSkipVerify disables SSL certificate verification
func WithKeyLogFile ¶ added in v1.6.0
func WithKeyLogFile(path string) SessionOption
WithKeyLogFile sets the path to write TLS key log for Wireshark decryption. This overrides the global SSLKEYLOGFILE environment variable for this session.
func WithLocalAddrIP ¶ added in v1.6.6
func WithLocalAddrIP(ip net.IP) SessionOption
WithLocalAddrIP is the net.IP-typed equivalent of WithLocalAddress. Pass the parsed IP directly when you already have a net.IP value (e.g. when rotating from a precomputed pool). Same semantics: nil is a no-op so callers building options conditionally don't accidentally clobber a previously-set address.
func WithLocalAddress ¶ added in v1.6.0
func WithLocalAddress(addr string) SessionOption
WithLocalAddress binds outgoing connections to a specific local IP address. Useful for IPv6 rotation when you have a large IPv6 prefix and want to rotate source IPs per session. On Linux, freebind is automatically applied so you can bind to any address from a routed prefix without configuring each one on the interface. Supports both IPv4 and IPv6 addresses (e.g., "192.168.1.100" or "2001:db8::1").
func WithQuicIdleTimeout ¶ added in v1.5.8
func WithQuicIdleTimeout(d time.Duration) SessionOption
WithQuicIdleTimeout sets the QUIC connection idle timeout. Default is 30 seconds (matches Chrome). Connections are closed after this duration of inactivity. Set higher values if you need longer-lived HTTP/3 connections with gaps between requests.
func WithRedirects ¶ added in v1.0.1
func WithRedirects(follow bool, maxRedirects int) SessionOption
WithRedirects configures redirect behavior
func WithRetry ¶ added in v1.0.1
func WithRetry(count int) SessionOption
WithRetry enables retry with default settings
func WithRetryConfig ¶ added in v1.0.1
func WithRetryConfig(count int, waitMin, waitMax time.Duration, retryOnStatus []int) SessionOption
WithRetryConfig configures retry behavior
func WithSessionCache ¶ added in v1.5.8
func WithSessionCache(backend transport.SessionCacheBackend, errorCallback transport.ErrorCallback) SessionOption
WithSessionCache sets a distributed TLS session cache backend. This enables TLS session ticket sharing across multiple instances (e.g., via Redis). The errorCallback is optional and will be called when backend operations fail.
func WithSessionPreferIPv4 ¶ added in v1.1.2
func WithSessionPreferIPv4() SessionOption
WithSessionPreferIPv4 makes the session prefer IPv4 addresses over IPv6. Use this on networks with poor IPv6 connectivity.
func WithSessionProxy ¶
func WithSessionProxy(proxyURL string) SessionOption
WithSessionProxy sets a proxy for the session
func WithSessionTCPProxy ¶ added in v1.5.3
func WithSessionTCPProxy(proxyURL string) SessionOption
WithSessionTCPProxy sets a proxy for TCP-based protocols (HTTP/1.1 and HTTP/2). Use this with WithSessionUDPProxy for split proxy configuration.
func WithSessionTimeout ¶
func WithSessionTimeout(d time.Duration) SessionOption
WithSessionTimeout sets the timeout for session requests
func WithSessionUDPProxy ¶ added in v1.5.3
func WithSessionUDPProxy(proxyURL string) SessionOption
WithSessionUDPProxy sets a proxy for UDP-based protocols (HTTP/3 via MASQUE). Use this with WithSessionTCPProxy for split proxy configuration.
func WithSwitchProtocol ¶ added in v1.6.0
func WithSwitchProtocol(protocol string) SessionOption
WithSwitchProtocol sets the protocol to switch to after Refresh(). This enables warming up TLS tickets on one protocol (e.g. H3) then serving requests on another (e.g. H2) with TLS session resumption. Valid values: "h1", "h2", "h3".
func WithTCPFingerprint ¶ added in v1.6.1
func WithTCPFingerprint(fp fingerprint.TCPFingerprint) SessionOption
WithCustomFingerprint sets a custom TLS/HTTP2 fingerprint for the session. When JA3 is set, TLS-only mode is automatically enabled (preset HTTP headers are skipped). WithTCPFingerprint overrides individual TCP/IP fingerprint fields from the preset. Only non-zero fields are applied; zero fields keep the preset default.
func WithTLSOnly ¶ added in v1.5.8
func WithTLSOnly() SessionOption
WithTLSOnly enables TLS-only mode. In this mode, the preset's TLS fingerprint is used but its default HTTP headers are NOT applied. You must set all headers manually per-request. Useful when you need full control over HTTP headers while keeping the TLS fingerprint.
func WithoutConditionalCache ¶ added in v1.6.7
func WithoutConditionalCache() SessionOption
WithoutConditionalCache disables the session's ETag / If-Modified-Since handling for the lifetime of the session. When set, the session never injects If-None-Match or If-Modified-Since headers and never stores those validators from responses.
Useful for benchmarking, fingerprint testing, or any workflow that needs every request to hit the origin fresh regardless of prior responses. Toggle the same state at runtime with Session.SetConditionalCacheEnabled, or skip the cache for a single request via Request.DisableConditionalCache.
func WithoutCookieJar ¶ added in v1.6.6
func WithoutCookieJar() SessionOption
WithoutCookieJar disables the session's internal cookie jar entirely. When set, Set-Cookie headers from responses are NOT stored and the jar's contents are NOT injected as Cookie headers on subsequent requests — cookie management is left fully to the caller via per-request headers.
Useful when an application maintains its own cookie store (database, shared cache across sessions) and wants the lib to be byte-transparent about cookies. Combine with the regular `headers={"Cookie": "..."}` kwarg to inject your own jar's contents per request.
Caller-provided Cookie headers always pass through regardless of this option — only the auto-injection from the internal jar is suppressed.
func WithoutRedirects ¶ added in v1.0.1
func WithoutRedirects() SessionOption
WithoutRedirects disables automatic redirect following
func WithoutRetry ¶ added in v1.0.5
func WithoutRetry() SessionOption
WithoutRetry explicitly disables retry
type StreamResponse ¶ added in v1.5.3
type StreamResponse struct {
StatusCode int
Headers map[string][]string
FinalURL string
Protocol string
ContentLength int64 // -1 if unknown (chunked encoding)
// contains filtered or unexported fields
}
StreamResponse represents a streaming HTTP response where the body is read incrementally. Use this for large file downloads.
func (*StreamResponse) Close ¶ added in v1.5.3
func (r *StreamResponse) Close() error
Close closes the response body - must be called when done
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
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client provides an HTTP client with browser TLS/HTTP fingerprint spoofing.
|
Package client provides an HTTP client with browser TLS/HTTP fingerprint spoofing. |
|
examples
|
|
|
go-examples/basic
command
Example: Basic HTTP requests with httpcloak
|
Example: Basic HTTP requests with httpcloak |
|
go-examples/browserleaks-ech
command
Example: ECH + 0-RTT test with browserleaks using HTTP/3
|
Example: ECH + 0-RTT test with browserleaks using HTTP/3 |
|
go-examples/cloudflare
command
Example: Multiple requests to Cloudflare trace endpoint
|
Example: Multiple requests to Cloudflare trace endpoint |
|
go-examples/custom-fingerprint
command
Example: Custom JA3 & Akamai Fingerprinting with httpcloak
|
Example: Custom JA3 & Akamai Fingerprinting with httpcloak |
|
go-examples/high-performance
command
Example: High-Performance Downloads
|
Example: High-Performance Downloads |
|
go-examples/new-features
command
|
|
|
go-examples/proxy-switching
command
|
|
|
go-examples/quic-idle-timeout
command
Example: QUIC Idle Timeout Configuration
|
Example: QUIC Idle Timeout Configuration |
|
go-examples/session
command
Example: Session management with cookies
|
Example: Session management with cookies |
|
go-examples/session-resumption
command
Example: Session Resumption (0-RTT)
|
Example: Session Resumption (0-RTT) |
|
go-examples/streaming
command
Example: Streaming Downloads with httpcloak
|
Example: Streaming Downloads with httpcloak |
|
go-examples/tls-only
command
Example: TLS-Only Mode with httpcloak
|
Example: TLS-Only Mode with httpcloak |
|
go-examples/warmup-and-fork
command
Warmup & Fork: Browser-Like Page Load and Parallel Tab Simulation
|
Warmup & Fork: Browser-Like Page Load and Parallel Tab Simulation |
|
Package protocol defines the JSON-shaped session configuration types that the cgo entry points in bindings/clib consume from the language SDKs.
|
Package protocol defines the JSON-shaped session configuration types that the cgo entry points in bindings/clib consume from the language SDKs. |
|
keylog.go provides TLS key logging for traffic analysis with Wireshark.
|
keylog.go provides TLS key logging for traffic analysis with Wireshark. |