Documentation
¶
Overview ¶
Package client provides an HTTP client with browser TLS/HTTP fingerprint spoofing.
This package is the core of httpcloak. It provides an HTTP client that mimics real browser fingerprints at the TLS and HTTP/2 protocol levels, making requests indistinguishable from actual Chrome, Firefox, or Safari browsers.
Why Fingerprint Spoofing Matters ¶
Modern bot detection systems analyze multiple layers of your HTTP connection:
- TLS Fingerprint (JA3/JA4): Cipher suites, extensions, elliptic curves
- HTTP/2 Fingerprint (Akamai): SETTINGS frame values, WINDOW_UPDATE, PRIORITY
- Header Fingerprint: Order, format, and values of HTTP headers
Go's standard library has a distinct fingerprint that bot detection systems (Cloudflare, Akamai, PerimeterX) can identify instantly. This package solves that by using uTLS for TLS spoofing and custom HTTP/2 framing.
Basic Usage ¶
c := client.NewClient("chrome-143")
defer c.Close()
resp, err := c.Get(ctx, "https://example.com", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Text())
Session Usage (with cookies) ¶
session := client.NewSession("chrome-143")
defer session.Close()
// Login - cookies are persisted
session.Post(ctx, "https://example.com/login", body, headers)
// Subsequent requests include cookies
resp, _ := session.Get(ctx, "https://example.com/dashboard", nil)
Package client options - configuration for the HTTP client.
The client uses functional options pattern for configuration. All options have sensible defaults, so you can create a client with just:
c := client.NewClient("chrome-143")
Or customize with options:
c := client.NewClient("chrome-143",
client.WithTimeout(60*time.Second),
client.WithProxy("http://proxy:8080"),
client.WithRetry(3),
)
Index ¶
- Variables
- func CalculateSPKIHash(cert *x509.Certificate) string
- func DecodeParams(query string) (map[string]string, error)
- func Decompress(data []byte, encoding string) ([]byte, error)
- func EncodeParams(params map[string]string) string
- func JoinURL(base, path string) string
- type Auth
- type BasicAuth
- type BearerAuth
- type CertPinError
- type CertPinner
- func (p *CertPinner) AddPin(hash string, opts ...PinOption) *CertPinner
- func (p *CertPinner) AddPinFromCertFile(certPath string, opts ...PinOption) error
- func (p *CertPinner) AddPinFromPEM(pemData []byte, opts ...PinOption) error
- func (p *CertPinner) Clear()
- func (p *CertPinner) GetPins() []*CertificatePin
- func (p *CertPinner) HasPins() bool
- func (p *CertPinner) Verify(host string, certs []*x509.Certificate) error
- type CertificatePin
- type Client
- func (c *Client) CertPinner() *CertPinner
- func (c *Client) ClearCookies()
- func (c *Client) ClearHooks()
- func (c *Client) ClearPins()
- func (c *Client) Close()
- func (c *Client) Cookies() *CookieJar
- func (c *Client) DisableCookies()
- func (c *Client) Do(ctx context.Context, req *Request) (*Response, error)
- func (c *Client) DoStream(ctx context.Context, req *Request) (*StreamResponse, error)
- func (c *Client) EnableCookies()
- func (c *Client) Get(ctx context.Context, url string, headers map[string]string) (*Response, error)
- func (c *Client) GetStream(ctx context.Context, url string, headers map[string]string) (*StreamResponse, error)
- func (c *Client) Hooks() *Hooks
- func (c *Client) OnPostResponse(hook PostResponseHook) *Client
- func (c *Client) OnPreRequest(hook PreRequestHook) *Client
- func (c *Client) PinCertificate(hash string, opts ...PinOption) *Client
- func (c *Client) PinCertificateFromFile(certPath string, opts ...PinOption) error
- func (c *Client) Post(ctx context.Context, url string, body []byte, headers map[string]string) (*Response, error)
- func (c *Client) Prepare(ctx context.Context, req *Request) (*PreparedRequest, error)
- func (c *Client) PrepareGet(ctx context.Context, url string, headers map[string]string) (*PreparedRequest, error)
- func (c *Client) PreparePost(ctx context.Context, url string, body []byte, headers map[string]string) (*PreparedRequest, error)
- func (c *Client) SetAuth(auth Auth)
- func (c *Client) SetBasicAuth(username, password string)
- func (c *Client) SetBearerAuth(token string)
- func (c *Client) SetPreset(presetName string)
- func (c *Client) SetTimeout(timeout time.Duration)
- func (c *Client) Stats() map[string]struct{ ... }
- type ClientConfig
- type Cookie
- type CookieJar
- func (j *CookieJar) AllCookies() map[string][]*Cookie
- func (j *CookieJar) Clear()
- func (j *CookieJar) ClearDomain(domain string)
- func (j *CookieJar) ClearExpired()
- func (j *CookieJar) CookieHeader(u *url.URL) string
- func (j *CookieJar) Cookies(u *url.URL) []*Cookie
- func (j *CookieJar) Count() int
- func (j *CookieJar) SetCookie(u *url.URL, name, value string)
- func (j *CookieJar) SetCookies(u *url.URL, cookies []*Cookie)
- func (j *CookieJar) SetCookiesFromHeaderList(u *url.URL, setCookieHeaders []string)
- func (j *CookieJar) SetCookiesFromHeaders(u *url.URL, headers map[string]string)
- type DigestAuth
- type FetchMode
- type FetchSite
- type FormData
- func (f *FormData) AddField(name, value string) *FormData
- func (f *FormData) AddFile(fieldName, fileName string, content []byte) *FormData
- func (f *FormData) AddFilePath(fieldName, filePath string) error
- func (f *FormData) AddFileReader(fieldName, fileName string, content io.Reader, mimeType string) *FormData
- func (f *FormData) Encode() ([]byte, string, error)
- type FormFile
- type HTTP3Client
- func (c *HTTP3Client) Close()
- func (c *HTTP3Client) Do(ctx context.Context, req *Request) (*Response, error)
- func (c *HTTP3Client) Get(ctx context.Context, url string, headers map[string]string) (*Response, error)
- func (c *HTTP3Client) Post(ctx context.Context, url string, body []byte, headers map[string]string) (*Response, error)
- func (c *HTTP3Client) SetPreset(presetName string)
- func (c *HTTP3Client) SetTimeout(timeout time.Duration)
- func (c *HTTP3Client) Stats() map[string]struct{ ... }
- type HookType
- type Hooks
- func (h *Hooks) Clear()
- func (h *Hooks) ClearPostResponse()
- func (h *Hooks) ClearPreRequest()
- func (h *Hooks) OnPostResponse(hook PostResponseHook) *Hooks
- func (h *Hooks) OnPreRequest(hook PreRequestHook) *Hooks
- func (h *Hooks) RunPostResponse(resp *Response) error
- func (h *Hooks) RunPreRequest(req *http.Request) error
- type Option
- func WithDisableH3() Option
- func WithDisableHTTP3() Option
- func WithDisableKeepAlives() Option
- func WithForceHTTP1() Option
- func WithForceHTTP2() Option
- func WithInsecureSkipVerify() Option
- func WithPreferIPv4() Option
- func WithPreset(preset string) Option
- func WithProxy(proxyURL string) Option
- func WithRedirects(follow bool, maxRedirects int) Option
- func WithRetry(maxRetries int) Option
- func WithRetryConfig(maxRetries int, waitMin, waitMax time.Duration, retryOnStatus []int) Option
- func WithTLSConfig(tlsConfig *tls.Config) Option
- func WithTimeout(timeout time.Duration) Option
- func WithoutRedirects() Option
- type PinOption
- type PinType
- type PostResponseHook
- type PreRequestHook
- type PreparedRequest
- func (p *PreparedRequest) AddHeader(key, value string) *PreparedRequest
- func (p *PreparedRequest) DelHeader(key string) *PreparedRequest
- func (p *PreparedRequest) GetAllHeaders() http.Header
- func (p *PreparedRequest) GetHeader(key string) string
- func (p *PreparedRequest) Send(ctx context.Context) (*Response, error)
- func (p *PreparedRequest) SetAuth(auth Auth) *PreparedRequest
- func (p *PreparedRequest) SetBody(body []byte) *PreparedRequest
- func (p *PreparedRequest) SetForceProtocol(protocol Protocol) *PreparedRequest
- func (p *PreparedRequest) SetHeader(key, value string) *PreparedRequest
- func (p *PreparedRequest) SetTimeout(ms int64) *PreparedRequest
- type Protocol
- type RedirectInfo
- type Request
- type RequestError
- type Response
- type SSEEvent
- type SSEReader
- type StreamResponse
- type URLBuilder
Constants ¶
This section is empty.
Variables ¶
var EnableCookies = struct{}{}
EnableCookies is a marker to enable cookie jar in NewClient Use NewSession() instead for simpler API, or call client.EnableCookies() after creation
Functions ¶
func CalculateSPKIHash ¶
func CalculateSPKIHash(cert *x509.Certificate) string
CalculateSPKIHash calculates the SHA256 hash of a certificate's SPKI Returns base64-encoded hash (HPKP format)
func DecodeParams ¶
DecodeParams decodes a query string to a map of parameters
func Decompress ¶
Decompress decompresses response body based on Content-Encoding
func EncodeParams ¶
EncodeParams encodes a map of parameters to a query string
Types ¶
type Auth ¶
type Auth interface {
// Apply applies authentication to the request
Apply(req *http.Request) error
// HandleChallenge handles authentication challenge from 401 response
HandleChallenge(resp *http.Response, req *http.Request) (bool, error)
}
Auth interface for authentication methods
type BasicAuth ¶
BasicAuth implements HTTP Basic authentication
func NewBasicAuth ¶
NewBasicAuth creates a new BasicAuth
type BearerAuth ¶
type BearerAuth struct {
Token string
}
BearerAuth implements Bearer token authentication
func NewBearerAuth ¶
func NewBearerAuth(token string) *BearerAuth
NewBearerAuth creates a new BearerAuth
func (*BearerAuth) Apply ¶
func (a *BearerAuth) Apply(req *http.Request) error
Apply applies Bearer auth header to request
func (*BearerAuth) HandleChallenge ¶
HandleChallenge handles 401 response - Bearer auth doesn't retry
type CertPinError ¶
CertPinError is returned when certificate pinning verification fails
func (*CertPinError) Error ¶
func (e *CertPinError) Error() string
type CertPinner ¶
type CertPinner struct {
// contains filtered or unexported fields
}
CertPinner handles certificate pinning verification
func NewCertPinner ¶
func NewCertPinner() *CertPinner
NewCertPinner creates a new certificate pinner
func (*CertPinner) AddPin ¶
func (p *CertPinner) AddPin(hash string, opts ...PinOption) *CertPinner
AddPin adds a certificate pin hash should be base64-encoded SHA256 of the certificate's SPKI Example: "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
func (*CertPinner) AddPinFromCertFile ¶
func (p *CertPinner) AddPinFromCertFile(certPath string, opts ...PinOption) error
AddPinFromCertFile loads a certificate from file and pins its public key
func (*CertPinner) AddPinFromPEM ¶
func (p *CertPinner) AddPinFromPEM(pemData []byte, opts ...PinOption) error
AddPinFromPEM adds a pin from PEM-encoded certificate data
func (*CertPinner) GetPins ¶
func (p *CertPinner) GetPins() []*CertificatePin
GetPins returns all configured pins
func (*CertPinner) HasPins ¶
func (p *CertPinner) HasPins() bool
HasPins returns true if any pins are configured
func (*CertPinner) Verify ¶
func (p *CertPinner) Verify(host string, certs []*x509.Certificate) error
Verify checks if the certificate chain matches any pin
type CertificatePin ¶
type CertificatePin struct {
// Type of pin (SHA256 of SPKI or full certificate)
Type PinType
// Hash is the pin value (base64 or hex encoded)
Hash string
// Host is the hostname this pin applies to (optional, empty = all hosts)
Host string
// IncludeSubdomains applies pin to subdomains as well
IncludeSubdomains bool
}
CertificatePin represents a pinned certificate or public key
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client with connection pooling and fingerprint spoofing By default, it tries HTTP/3 first, then HTTP/2, then HTTP/1.1 as fallback
func NewClient ¶
NewClient creates a new HTTP client with default configuration Tries HTTP/3 first, then HTTP/2, then HTTP/1.1 as fallback
func NewSession ¶
NewSession creates a new HTTP client with cookie jar enabled (like requests.Session()) Cookies are automatically persisted between requests
func (*Client) CertPinner ¶
func (c *Client) CertPinner() *CertPinner
CertPinner returns the certificate pinner, creating one if needed
func (*Client) ClearCookies ¶
func (c *Client) ClearCookies()
ClearCookies removes all cookies from the jar
func (*Client) DisableCookies ¶
func (c *Client) DisableCookies()
DisableCookies disables cookie handling
func (*Client) Do ¶
Do executes an HTTP request Tries HTTP/3 first, falls back to HTTP/2 if HTTP/3 fails
func (*Client) DoStream ¶
DoStream executes an HTTP request and returns a streaming response The caller is responsible for closing the response
func (*Client) EnableCookies ¶
func (c *Client) EnableCookies()
EnableCookies enables cookie jar for session persistence
func (*Client) GetStream ¶
func (c *Client) GetStream(ctx context.Context, url string, headers map[string]string) (*StreamResponse, error)
GetStream performs a streaming GET request
func (*Client) OnPostResponse ¶
func (c *Client) OnPostResponse(hook PostResponseHook) *Client
OnPostResponse adds a post-response hook Hook is called after each response is received
func (*Client) OnPreRequest ¶
func (c *Client) OnPreRequest(hook PreRequestHook) *Client
OnPreRequest adds a pre-request hook Hook is called before each request is sent
func (*Client) PinCertificate ¶
PinCertificate adds a certificate pin hash should be base64-encoded SHA256 of the certificate's SPKI Example: c.PinCertificate("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", ForHost("example.com"))
func (*Client) PinCertificateFromFile ¶
PinCertificateFromFile loads a certificate from file and pins its public key
func (*Client) Post ¶
func (c *Client) Post(ctx context.Context, url string, body []byte, headers map[string]string) (*Response, error)
Post performs a POST request
func (*Client) Prepare ¶
Prepare creates a PreparedRequest from a Request The PreparedRequest can be inspected, modified, and then sent
func (*Client) PrepareGet ¶
func (c *Client) PrepareGet(ctx context.Context, url string, headers map[string]string) (*PreparedRequest, error)
PrepareGet creates a prepared GET request
func (*Client) PreparePost ¶
func (c *Client) PreparePost(ctx context.Context, url string, body []byte, headers map[string]string) (*PreparedRequest, error)
PreparePost creates a prepared POST request
func (*Client) SetBasicAuth ¶
SetBasicAuth sets Basic authentication
func (*Client) SetBearerAuth ¶
SetBearerAuth sets Bearer token authentication
func (*Client) SetTimeout ¶
SetTimeout sets the request timeout
type ClientConfig ¶
type ClientConfig struct {
// Preset is the browser fingerprint preset name (e.g., "chrome-143", "firefox-133").
// This determines the TLS fingerprint (JA3/JA4), HTTP/2 settings, and default headers.
Preset string
// Timeout is the maximum duration for a request including redirects.
// Default: 30 seconds.
Timeout time.Duration
// Proxy is the URL of the proxy server.
// Supports http://, https://, and socks5:// schemes.
// Example: "http://user:pass@proxy.example.com:8080"
Proxy string
// FollowRedirects controls whether the client follows HTTP redirects (3xx responses).
// Default: true.
FollowRedirects bool
// MaxRedirects is the maximum number of redirects to follow.
// Prevents infinite redirect loops.
// Default: 10.
MaxRedirects int
// RetryEnabled enables automatic retry on transient failures.
// When enabled, uses exponential backoff with jitter.
// Default: false.
RetryEnabled bool
// MaxRetries is the maximum number of retry attempts.
// Default: 3.
MaxRetries int
// RetryWaitMin is the minimum wait time between retries.
// The actual wait is calculated using exponential backoff.
// Default: 1 second.
RetryWaitMin time.Duration
// RetryWaitMax is the maximum wait time between retries.
// Caps the exponential backoff.
// Default: 30 seconds.
RetryWaitMax time.Duration
// RetryOnStatus is the list of HTTP status codes that trigger a retry.
// Default: [429, 500, 502, 503, 504].
RetryOnStatus []int
// InsecureSkipVerify disables TLS certificate verification.
// WARNING: This makes the connection insecure. Only use for testing.
// Default: false.
InsecureSkipVerify bool
// TLSConfig is a custom TLS configuration for advanced use cases.
// Most users should not need to set this.
TLSConfig *tls.Config
// DisableKeepAlives disables HTTP keep-alives.
// When true, each request opens a new connection.
// Default: false.
DisableKeepAlives bool
// DisableH3 disables HTTP/3 (QUIC) and forces HTTP/2.
// Useful if HTTP/3 causes issues with certain servers.
// Default: false.
DisableH3 bool
// PreferIPv4 makes the client prefer IPv4 addresses over IPv6.
// Useful on networks with poor IPv6 connectivity.
// Default: false (prefers IPv6 like modern browsers).
PreferIPv4 bool
}
ClientConfig holds all configuration options for the HTTP client. Use functional options (WithTimeout, WithProxy, etc.) to set these values.
func DefaultConfig ¶
func DefaultConfig() *ClientConfig
DefaultConfig returns default client configuration
type Cookie ¶
type Cookie struct {
Name string
Value string
Domain string
Path string
Expires time.Time
MaxAge int // seconds
Secure bool
HttpOnly bool
SameSite string // "Strict", "Lax", "None"
Raw string // original Set-Cookie header
}
Cookie represents an HTTP cookie
func ParseSetCookie ¶
ParseSetCookie parses a Set-Cookie header value into a Cookie
type CookieJar ¶
type CookieJar struct {
// contains filtered or unexported fields
}
CookieJar stores cookies and provides thread-safe access
func (*CookieJar) AllCookies ¶
AllCookies returns all cookies in the jar (for debugging)
func (*CookieJar) ClearDomain ¶
ClearDomain removes all cookies for a specific domain
func (*CookieJar) ClearExpired ¶
func (j *CookieJar) ClearExpired()
ClearExpired removes all expired cookies
func (*CookieJar) CookieHeader ¶
CookieHeader returns the Cookie header value for the given URL
func (*CookieJar) SetCookies ¶
SetCookies adds cookies from Set-Cookie headers to the jar
func (*CookieJar) SetCookiesFromHeaderList ¶
SetCookiesFromHeaderList handles multiple Set-Cookie headers
type DigestAuth ¶
type DigestAuth struct {
Username string
Password string
// contains filtered or unexported fields
}
DigestAuth implements HTTP Digest authentication
func NewDigestAuth ¶
func NewDigestAuth(username, password string) *DigestAuth
NewDigestAuth creates a new DigestAuth
func (*DigestAuth) Apply ¶
func (a *DigestAuth) Apply(req *http.Request) error
Apply applies Digest auth header to request (if challenge has been received)
func (*DigestAuth) HandleChallenge ¶
HandleChallenge parses WWW-Authenticate header and prepares auth
type FetchMode ¶
type FetchMode int
FetchMode specifies the Sec-Fetch-Mode behavior
const ( FetchModeCORS // XHR/fetch call (sec-fetch-mode: cors) )
type FormData ¶
type FormData struct {
Fields map[string]string // Regular form fields
Files []FormFile // Files to upload
}
FormData represents multipart form data
func (*FormData) AddFilePath ¶
AddFilePath adds a file from a filesystem path
type FormFile ¶
type FormFile struct {
FieldName string // Form field name
FileName string // File name
Content io.Reader // File content
MIMEType string // MIME type (optional, will be detected)
}
FormFile represents a file to upload
type HTTP3Client ¶
type HTTP3Client struct {
// contains filtered or unexported fields
}
HTTP3Client is an HTTP/3 client with QUIC connection pooling
func NewHTTP3Client ¶
func NewHTTP3Client(presetName string) *HTTP3Client
NewHTTP3Client creates a new HTTP/3 client
func NewHTTP3ClientWithDNS ¶
func NewHTTP3ClientWithDNS(presetName string, dnsCache interface{}) *HTTP3Client
NewHTTP3ClientWithDNS creates a new HTTP/3 client with shared DNS cache
func (*HTTP3Client) Close ¶
func (c *HTTP3Client) Close()
Close shuts down the client and all connections
func (*HTTP3Client) Get ¶
func (c *HTTP3Client) Get(ctx context.Context, url string, headers map[string]string) (*Response, error)
Get performs a GET request over HTTP/3
func (*HTTP3Client) Post ¶
func (c *HTTP3Client) Post(ctx context.Context, url string, body []byte, headers map[string]string) (*Response, error)
Post performs a POST request over HTTP/3
func (*HTTP3Client) SetPreset ¶
func (c *HTTP3Client) SetPreset(presetName string)
SetPreset changes the fingerprint preset
func (*HTTP3Client) SetTimeout ¶
func (c *HTTP3Client) SetTimeout(timeout time.Duration)
SetTimeout sets the request timeout
type Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks holds request hooks
func (*Hooks) ClearPostResponse ¶
func (h *Hooks) ClearPostResponse()
ClearPostResponse removes all post-response hooks
func (*Hooks) ClearPreRequest ¶
func (h *Hooks) ClearPreRequest()
ClearPreRequest removes all pre-request hooks
func (*Hooks) OnPostResponse ¶
func (h *Hooks) OnPostResponse(hook PostResponseHook) *Hooks
OnPostResponse adds a post-response hook Hook is called after each response is received Can be used to log responses, collect metrics, etc.
func (*Hooks) OnPreRequest ¶
func (h *Hooks) OnPreRequest(hook PreRequestHook) *Hooks
OnPreRequest adds a pre-request hook Hook is called before each request is sent Can be used to modify headers, log requests, etc.
func (*Hooks) RunPostResponse ¶
RunPostResponse runs all post-response hooks
type Option ¶
type Option func(*ClientConfig)
Option is a function that modifies ClientConfig
func WithDisableH3 ¶ added in v1.0.1
func WithDisableH3() Option
WithDisableH3 disables HTTP/3 (alias for WithDisableHTTP3)
func WithDisableHTTP3 ¶
func WithDisableHTTP3() Option
WithDisableHTTP3 disables HTTP/3 and forces HTTP/2
func WithDisableKeepAlives ¶
func WithDisableKeepAlives() Option
WithDisableKeepAlives disables HTTP keep-alives
func WithForceHTTP2 ¶
func WithForceHTTP2() Option
WithForceHTTP2 forces HTTP/2 for all requests (disables HTTP/3, still allows HTTP/1.1 fallback) This is useful when you want to ensure HTTP/2 is used without attempting HTTP/3
func WithInsecureSkipVerify ¶
func WithInsecureSkipVerify() Option
WithInsecureSkipVerify disables TLS certificate verification WARNING: This makes the connection insecure and should only be used for testing
func WithPreferIPv4 ¶ added in v1.0.1
func WithPreferIPv4() Option
WithPreferIPv4 makes the client prefer IPv4 addresses over IPv6. Use this on networks with poor IPv6 connectivity.
func WithRedirects ¶
WithRedirects configures redirect behavior
func WithRetryConfig ¶
WithRetryConfig configures retry behavior
func WithTLSConfig ¶
WithTLSConfig sets a custom TLS configuration
func WithTimeout ¶
WithTimeout sets the request timeout
func WithoutRedirects ¶
func WithoutRedirects() Option
WithoutRedirects disables automatic redirect following
type PinOption ¶
type PinOption func(*CertificatePin)
PinOption configures a certificate pin
func IncludeSubdomains ¶
func IncludeSubdomains() PinOption
IncludeSubdomains applies the pin to subdomains as well
type PostResponseHook ¶
PostResponseHook is called after a response is received It receives the Response and can inspect/modify it Return an error to signal a problem (won't affect the response)
type PreRequestHook ¶
PreRequestHook is called before a request is sent It receives the http.Request and can modify it Return an error to abort the request
type PreparedRequest ¶
type PreparedRequest struct {
// The underlying http.Request
HTTPRequest *http.Request
// Original request data (for reference)
Method string
URL string
Headers map[string]string
Body []byte
// Configuration
Timeout int64 // Timeout in milliseconds
ForceProtocol Protocol // Forced protocol
FetchMode FetchMode
FetchSite FetchSite
Referer string
Auth Auth
// Redirect settings
FollowRedirects bool
MaxRedirects int
// contains filtered or unexported fields
}
PreparedRequest is a request that has been prepared for sending It allows inspection and modification before actual execution
func (*PreparedRequest) AddHeader ¶
func (p *PreparedRequest) AddHeader(key, value string) *PreparedRequest
AddHeader adds a header to the prepared request (allows multiple values)
func (*PreparedRequest) DelHeader ¶
func (p *PreparedRequest) DelHeader(key string) *PreparedRequest
DelHeader removes a header from the prepared request
func (*PreparedRequest) GetAllHeaders ¶
func (p *PreparedRequest) GetAllHeaders() http.Header
GetAllHeaders returns all headers
func (*PreparedRequest) GetHeader ¶
func (p *PreparedRequest) GetHeader(key string) string
GetHeader gets a header value from the prepared request
func (*PreparedRequest) Send ¶
func (p *PreparedRequest) Send(ctx context.Context) (*Response, error)
Send executes the prepared request
func (*PreparedRequest) SetAuth ¶
func (p *PreparedRequest) SetAuth(auth Auth) *PreparedRequest
SetAuth sets authentication on the prepared request
func (*PreparedRequest) SetBody ¶
func (p *PreparedRequest) SetBody(body []byte) *PreparedRequest
SetBody sets a new body on the prepared request
func (*PreparedRequest) SetForceProtocol ¶
func (p *PreparedRequest) SetForceProtocol(protocol Protocol) *PreparedRequest
SetForceProtocol sets the forced protocol
func (*PreparedRequest) SetHeader ¶
func (p *PreparedRequest) SetHeader(key, value string) *PreparedRequest
SetHeader sets a header on the prepared request
func (*PreparedRequest) SetTimeout ¶
func (p *PreparedRequest) SetTimeout(ms int64) *PreparedRequest
SetTimeout sets the timeout in milliseconds
type RedirectInfo ¶
RedirectInfo stores information about a redirect
type Request ¶
type Request struct {
Method string
URL string
Headers map[string]string
Body []byte
Timeout time.Duration
// Customization options
UserAgent string // Override User-Agent (empty = use preset)
ForceProtocol Protocol // Force specific protocol (ProtocolAuto = auto)
FetchMode FetchMode // Fetch mode: Navigate (default, human click) or CORS (XHR/fetch)
FetchSite FetchSite // Sec-Fetch-Site: Auto (default), None, SameOrigin, SameSite, CrossSite
Referer string // Referer header (used for auto-detecting FetchSite)
// Authentication (overrides client-level auth)
Auth Auth
// Params adds query parameters to the URL
Params map[string]string
// Per-request redirect override (nil = use client config)
FollowRedirects *bool
MaxRedirects int
// Per-request retry override (nil = use client config)
DisableRetry bool
}
Request represents an HTTP request
type RequestError ¶
RequestError represents a request-level error
func (*RequestError) Error ¶
func (e *RequestError) Error() string
type Response ¶
type Response struct {
StatusCode int
Headers map[string]string
Body []byte
FinalURL string
Timing *protocol.Timing
Protocol string // "h3" or "h2"
// Request info
Request *Request
// Redirect history
RedirectHistory []*RedirectInfo
}
Response represents an HTTP response
func (*Response) IsClientError ¶
IsClientError returns true if the status code is 4xx
func (*Response) IsRedirect ¶
IsRedirect returns true if the status code is 3xx
func (*Response) IsServerError ¶
IsServerError returns true if the status code is 5xx
type SSEReader ¶
type SSEReader struct {
// contains filtered or unexported fields
}
SSEReader provides Server-Sent Events parsing
func NewSSEReader ¶
func NewSSEReader(resp *StreamResponse) *SSEReader
NewSSEReader creates an SSE reader from a streaming response
type StreamResponse ¶
type StreamResponse struct {
StatusCode int
Headers map[string]string
FinalURL string
Timing *protocol.Timing
Protocol string
// Request info
Request *Request
// contains filtered or unexported fields
}
StreamResponse represents a streaming HTTP response
func (*StreamResponse) Close ¶
func (r *StreamResponse) Close() error
Close closes the response body and cancels the context
func (*StreamResponse) IsSuccess ¶
func (r *StreamResponse) IsSuccess() bool
IsSuccess returns true if the status code is 2xx
func (*StreamResponse) Lines ¶
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 ¶
func (r *StreamResponse) Read(p []byte) (n int, err error)
Read reads data from the response body
func (*StreamResponse) ReadAll ¶
func (r *StreamResponse) ReadAll() ([]byte, error)
ReadAll reads the entire response body into memory
func (*StreamResponse) Scanner ¶
func (r *StreamResponse) Scanner() *bufio.Scanner
Scanner returns a bufio.Scanner for line-by-line reading
type URLBuilder ¶
type URLBuilder struct {
// contains filtered or unexported fields
}
URLBuilder helps build URLs with query parameters
func NewURLBuilder ¶
func NewURLBuilder(baseURL string) *URLBuilder
NewURLBuilder creates a new URLBuilder from a base URL
func (*URLBuilder) AddParam ¶
func (b *URLBuilder) AddParam(key, value string) *URLBuilder
AddParam adds a query parameter (allows multiple values for same key)
func (*URLBuilder) BuildSorted ¶
func (b *URLBuilder) BuildSorted() string
BuildSorted builds the final URL with sorted query parameters Useful for consistent URL generation (e.g., for caching)
func (*URLBuilder) Param ¶
func (b *URLBuilder) Param(key, value string) *URLBuilder
Param adds a single query parameter
func (*URLBuilder) Params ¶
func (b *URLBuilder) Params(params map[string]string) *URLBuilder
Params adds multiple query parameters from a map