Documentation
¶
Overview ¶
Package requests is a Go port of the curl_cffi.requests API. It provides a requests-like Session with browser TLS/HTTP fingerprint impersonation.
Index ¶
- Constants
- Variables
- func IsTimeout(err error) bool
- func NewRequestException(msg string, code int, rsp *Response) error
- func UseBrowser(newRenderer func(sess *Session) BrowserRenderer)
- type BasicAuth
- type BrowserRenderer
- type CertificateVerifyError
- type ClientCert
- type ConnectionError
- type Cookie
- type CookieTypes
- type Cookies
- func (c *Cookies) Del(name string)
- func (c *Cookies) Get(name string) (string, bool)
- func (c *Cookies) GetCookie(name string) (*Cookie, bool)
- func (c *Cookies) Items() []Cookie
- func (c *Cookies) Len() int
- func (c *Cookies) Map() map[string]string
- func (c *Cookies) Set(name, value string)
- func (c *Cookies) SetCookie(ck Cookie)
- func (c *Cookies) String() string
- func (c *Cookies) Update(other CookieTypes)
- type DNSError
- type ExtraFingerprints
- type HTTPError
- type HeaderPair
- type HeaderTypes
- type Headers
- func (h *Headers) Add(name, value string)
- func (h *Headers) Clone() *Headers
- func (h *Headers) Del(name string)
- func (h *Headers) Get(name string) string
- func (h *Headers) GetList(name string) []string
- func (h *Headers) Has(name string) bool
- func (h *Headers) Items() map[string]string
- func (h *Headers) Keys() []string
- func (h *Headers) Len() int
- func (h *Headers) MultiItems() []HeaderPair
- func (h *Headers) Set(name, value string)
- func (h *Headers) String() string
- func (h *Headers) Update(other HeaderTypes)
- type ImpersonateError
- type IncompleteRead
- type InterfaceError
- type InvalidSchema
- type InvalidURL
- type Option
- func WithAcceptEncoding(v string) Option
- func WithAkamai(s string) Option
- func WithAllowRedirects(v bool) Option
- func WithAuth(username, password string) Option
- func WithBaseURL(u string) Option
- func WithBrowser() Option
- func WithCert(certFile, keyFile string) Option
- func WithContent(v any) Option
- func WithContentCallback(fn func([]byte) error) Option
- func WithCookies(cookieTypes CookieTypes) Option
- func WithData(v any) Option
- func WithDebug(v bool) Option
- func WithDefaultEncoding(enc string) Option
- func WithDefaultHeaders(v bool) Option
- func WithDiscardCookies(v bool) Option
- func WithExtraFP(fp *ExtraFingerprints) Option
- func WithHTTPVersion(v string) Option
- func WithHeader(name, value string) Option
- func WithHeaders(h HeaderTypes) Option
- func WithImpersonate(name string) Option
- func WithInterface(name string) Option
- func WithJA3(s string) Option
- func WithJSON(v any) Option
- func WithMaxRecvSpeed(n int) Option
- func WithMaxRedirects(n int) Option
- func WithParams(p any) Option
- func WithProxies(p map[string]string) Option
- func WithProxy(proxyURL string) Option
- func WithProxyAuth(username, password string) Option
- func WithQuote(v any) Option
- func WithRaiseForStatus(v bool) Option
- func WithReferer(r string) Option
- func WithRetry(n int) Option
- func WithStream(v bool) Option
- func WithTimeout(d time.Duration) Option
- func WithTimeoutSeconds(s float64) Option
- func WithTrustEnv(v bool) Option
- func WithVerify(v bool) Option
- type Param
- type Params
- type ProxyError
- type Request
- type RequestException
- type RequestTypes
- type Response
- func Browse(req RequestTypes, opts ...Option) (*Response, error)
- func Delete(rawURL string, opts ...Option) (*Response, error)
- func Do(method, rawURL string, opts ...Option) (*Response, error)
- func Get(rawURL string, opts ...Option) (*Response, error)
- func Head(rawURL string, opts ...Option) (*Response, error)
- func NewResponse() *Response
- func Options(rawURL string, opts ...Option) (*Response, error)
- func Patch(rawURL string, opts ...Option) (*Response, error)
- func Post(rawURL string, opts ...Option) (*Response, error)
- func Put(rawURL string, opts ...Option) (*Response, error)
- func Send(req RequestTypes, opts ...Option) (*Response, error)
- func Trace(rawURL string, opts ...Option) (*Response, error)
- func (r *Response) CharsetEncoding() string
- func (r *Response) Close() error
- func (r *Response) ContentType() string
- func (r *Response) Encoding() string
- func (r *Response) HasHeader(name string) bool
- func (r *Response) IsRedirect() bool
- func (r *Response) IterContent() (func() ([]byte, error, bool), error)
- func (r *Response) IterLines(delimiter string) ([]string, error)
- func (r *Response) JSON(v any) error
- func (r *Response) Len() int
- func (r *Response) RaiseForStatus() error
- func (r *Response) ReadAll() ([]byte, error)
- func (r *Response) SetEncoding(enc string) error
- func (r *Response) String() string
- func (r *Response) Text() string
- type SSLError
- type Session
- func (s *Session) Browse(req RequestTypes, opts ...Option) (*Response, error)
- func (s *Session) Close()
- func (s *Session) Cookies() *Cookies
- func (s *Session) Delete(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Get(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Head(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Headers() *Headers
- func (s *Session) Options(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Patch(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Post(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Put(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Request(method, rawURL string, opts ...Option) (*Response, error)
- func (s *Session) Send(req RequestTypes, opts ...Option) (*Response, error)
- func (s *Session) SetCookies(c CookieTypes)
- func (s *Session) Trace(rawURL string, opts ...Option) (*Response, error)
- func (s *Session) UserAgent() string
- type SessionClosed
- type Timeout
- type TooManyRedirects
- type UnrewindableBodyError
- type UnsupportedOptionError
Constants ¶
const ( Chrome100 = impersonate.Chrome100 Chrome101 = impersonate.Chrome101 Chrome104 = impersonate.Chrome104 Chrome107 = impersonate.Chrome107 Chrome110 = impersonate.Chrome110 Chrome116 = impersonate.Chrome116 Chrome119 = impersonate.Chrome119 Chrome120 = impersonate.Chrome120 Chrome123 = impersonate.Chrome123 Chrome124 = impersonate.Chrome124 Chrome131 = impersonate.Chrome131 Chrome131Android = impersonate.Chrome131Android Chrome133a = impersonate.Chrome133a Chrome136 = impersonate.Chrome136 Chrome142 = impersonate.Chrome142 Chrome145 = impersonate.Chrome145 Chrome146 = impersonate.Chrome146 Chrome150 = impersonate.Chrome150 Chrome99 = impersonate.Chrome99 Chrome99Android = impersonate.Chrome99Android Custom = impersonate.Custom Edge101 = impersonate.Edge101 Edge99 = impersonate.Edge99 Firefox133 = impersonate.Firefox133 Firefox135 = impersonate.Firefox135 Firefox144 = impersonate.Firefox144 Firefox147 = impersonate.Firefox147 OkHTTP4Android = impersonate.OkHTTP4Android Safari153 = impersonate.Safari153 Safari155 = impersonate.Safari155 Safari170 = impersonate.Safari170 Safari172Ios = impersonate.Safari172Ios Safari180 = impersonate.Safari180 Safari180Ios = impersonate.Safari180Ios Safari184 = impersonate.Safari184 Safari184Ios = impersonate.Safari184Ios Safari260 = impersonate.Safari260 Safari2601 = impersonate.Safari2601 Safari260Ios = impersonate.Safari260Ios Tor145 = impersonate.Tor145 )
Impersonation targets, re-exported from the impersonate package so that a request needs one import rather than two:
sess.Send(requests.Request{
URL: "https://httpbun.com/get",
Impersonate: requests.Chrome146,
})
These are aliases of the constants in impersonate/targets.go, not a second copy of the values, so a preset change reaches both. TestTargetsMatchImpersonate fails if a target is added there and not here.
The Impersonate field is a plain string, so "chrome146" works too. Prefer a constant: a misspelt string is only caught when the request is made, whereas a misspelt constant does not compile. impersonate.Get reports an unknown target as an *ImpersonateError.
const ( DefaultChrome = impersonate.DefaultChrome DefaultEdge = impersonate.DefaultEdge DefaultSafari = impersonate.DefaultSafari DefaultSafariIOS = impersonate.DefaultSafariIOS DefaultSafariBeta = impersonate.DefaultSafariBeta DefaultSafariIOSBeta = impersonate.DefaultSafariIOSBeta DefaultChromeAndroid = impersonate.DefaultChromeAndroid DefaultFirefox = impersonate.DefaultFirefox DefaultTor = impersonate.DefaultTor )
The family defaults: the target each short alias resolves to, so "chrome" resolves to DefaultChrome. These are the better choice for an example or a default setting, because they follow the family as the presets are updated, where naming an exact version pins a browser that will age.
Variables ¶
var ErrTimeout = errors.New("requests: timeout")
ErrTimeout is a sentinel matching any Timeout error.
Functions ¶
func NewRequestException ¶
NewRequestException builds the most specific error for a transport failure.
func UseBrowser ¶
func UseBrowser(newRenderer func(sess *Session) BrowserRenderer)
UseBrowser installs the renderer that Request.Browser delegates to, one per session, so a page and a plain request on the same session share cookies. The browser package calls it from an init, and there is no reason to call it yourself: importing the browser package is what installs it.
Types ¶
type BrowserRenderer ¶
type BrowserRenderer interface {
// Send loads the request's URL and returns the page that settles, with the
// rendered document as the response body.
Send(req Request) (*Response, error)
// Close releases the renderer's browser.
Close()
}
BrowserRenderer is the browser a Request with Browser set is loaded in. The browser package installs one from its init, which is how this package stays free of a dependency on it: browser imports requests, so the reverse would be an import cycle.
type CertificateVerifyError ¶
type CertificateVerifyError struct{ *SSLError }
CertificateVerifyError indicates certificate validation failed.
type ClientCert ¶
ClientCert holds a client certificate and key file path.
type ConnectionError ¶
type ConnectionError struct{ *RequestException }
ConnectionError indicates a connection level failure.
type Cookie ¶
type Cookie struct {
Name string
Value string
Domain string
Path string
Secure bool
HTTPOnly bool
Expires time.Time
}
Cookie is a single HTTP cookie with the attributes curl_cffi tracks.
type Cookies ¶
type Cookies struct {
// contains filtered or unexported fields
}
Cookies is an ordered cookie collection. It mirrors curl_cffi's Cookies mapping (name -> attributes) closely enough for session handling.
func NewCookies ¶
func NewCookies(c CookieTypes) *Cookies
NewCookies builds a Cookies value from a map or an existing collection.
func (*Cookies) Update ¶
func (c *Cookies) Update(other CookieTypes)
Update merges cookies into the collection, replacing by name.
type DNSError ¶
type DNSError struct{ *ConnectionError }
DNSError indicates the host could not be resolved.
type ExtraFingerprints ¶
type ExtraFingerprints struct {
TLSMinVersion string
TLSGrease *bool
TLSPermuteExtensions *bool
TLSCertCompression string
TLSRecordSizeLimit int
HTTP2StreamWeight *int
HTTP2StreamExclusive *int
HTTP2NoPriority *bool
HeaderOrder string
SplitCookies *bool
}
ExtraFingerprints carries the per-request fingerprint overrides that curl_cffi exposes through extra_fp. Only the fields understood by this port are represented.
type HTTPError ¶
type HTTPError struct{ *RequestException }
HTTPError is returned by Response.raise_for_status for 4xx/5xx.
type HeaderPair ¶
HeaderPair is a single header line.
type HeaderTypes ¶
type HeaderTypes interface{}
HeaderTypes is the set of accepted header inputs: *Headers, Headers, []HeaderPair, map[string]string, or map[string][]string. Headers itself is a []string of "Name: Value" lines, so a plain []string is accepted too. A map loses ordering, so prefer Headers or []HeaderPair when order matters, as it usually does for impersonation. Anything else panics, so a caller finds out immediately rather than sending a request with headers silently missing.
type Headers ¶
type Headers []string
Headers is an ordered, case-insensitive HTTP header collection. It mirrors the behaviour of curl_cffi/httpx Headers: insertion order is preserved, lookups are case-insensitive and repeated keys can be retrieved with GetList.
It is a slice of "Name: Value" lines, so it can be written directly as a composite literal, which is how headers appear in HTTP and on a command line:
requests.Headers{
"Accept: application/json",
"X-Custom: value",
}
A value's leading and trailing spaces are not significant and are dropped when the line is read back, which matches how an HTTP parser treats them.
func NewHeaders ¶
func NewHeaders(h HeaderTypes) *Headers
NewHeaders builds ordered Headers from any supported input.
func (*Headers) MultiItems ¶
func (h *Headers) MultiItems() []HeaderPair
MultiItems returns every header line in order, without concatenation.
func (*Headers) Set ¶
Set replaces any existing value for name, keeping its position, or appends. The stored line takes the spelling of name that is passed in.
func (*Headers) Update ¶
func (h *Headers) Update(other HeaderTypes)
Update merges another header set, replacing any existing keys in place.
type ImpersonateError ¶
type ImpersonateError struct{ *RequestException }
ImpersonateError indicates the requested impersonation target is unknown or the TLS configuration failed.
type IncompleteRead ¶
type IncompleteRead struct{ *HTTPError }
IncompleteRead indicates the body was truncated.
type InterfaceError ¶
type InterfaceError struct{ *RequestException }
InterfaceError indicates the requested outgoing interface could not be used.
type InvalidSchema ¶
type InvalidSchema struct{ *RequestException }
InvalidSchema indicates an unsupported URL scheme.
type Option ¶
type Option func(*config)
Option configures a Session or a single request.
func WithAcceptEncoding ¶
WithAcceptEncoding sets the Accept-Encoding header. Pass an empty string to remove it and let the transport handle decompression.
func WithAkamai ¶
WithAkamai sets a custom Akamai HTTP/2 fingerprint string (advanced).
func WithAllowRedirects ¶
WithAllowRedirects controls whether redirects are followed.
func WithBaseURL ¶
WithBaseURL sets a base URL used to resolve relative request URLs.
func WithBrowser ¶
func WithBrowser() Option
WithBrowser loads the URL in the full browser instead of the fast client, so the page's scripts run and the body is the document as it settled. It is the option form of Request.Browser, and needs the browser package imported, which is what installs it.
func WithContent ¶
WithContent sets the raw request body, allowing streaming io.Reader bodies.
func WithContentCallback ¶
WithContentCallback is invoked for every body chunk as it arrives.
func WithCookies ¶
func WithCookies(cookieTypes CookieTypes) Option
WithCookies sets request cookies.
func WithData ¶
WithData sets the request body. Accepts string, []byte, io.Reader, map[string]string, url.Values or Params (the latter are form-encoded).
func WithDefaultEncoding ¶
WithDefaultEncoding sets the charset used to decode responses that lack an explicit charset.
func WithDefaultHeaders ¶
WithDefaultHeaders controls whether the impersonated browser's default headers are applied. User supplied headers always win.
func WithDiscardCookies ¶
WithDiscardCookies prevents server cookies from updating the session.
func WithExtraFP ¶
func WithExtraFP(fp *ExtraFingerprints) Option
WithExtraFP sets extra fingerprint overrides.
func WithHTTPVersion ¶
WithHTTPVersion selects the HTTP version: "v1", "v2", "v3".
func WithHeader ¶
WithHeader sets a single request header.
func WithImpersonate ¶
WithImpersonate selects a browser fingerprint preset to mimic.
func WithInterface ¶
WithInterface binds the outgoing connection to a network interface or local IP.
func WithMaxRecvSpeed ¶
WithMaxRecvSpeed limits the download rate in bytes per second.
func WithMaxRedirects ¶
WithMaxRedirects sets the maximum number of redirects (use -1 for unlimited).
func WithParams ¶
WithParams sets the query string. Accepts Params, url.Values, map[string]string or map[string][]string.
func WithProxies ¶
WithProxies sets per-scheme or per-host proxy URLs, e.g. {"http": "http://...", "https": "http://...", "all": "..."}.
func WithProxyAuth ¶
WithProxyAuth sets proxy credentials.
func WithQuote ¶
WithQuote controls URL percent-encoding behaviour (parity with curl_cffi's quote parameter). Pass false to disable automatic encoding.
Not implemented: setting it makes the request fail with an *UnsupportedOptionError rather than silently ignoring it.
func WithRaiseForStatus ¶
WithRaiseForStatus makes the request return an error for 4xx/5xx responses.
func WithStream ¶
WithStream keeps the response body unread so it can be consumed incrementally.
func WithTimeout ¶
WithTimeout sets the total request timeout.
func WithTimeoutSeconds ¶
WithTimeoutSeconds sets the total request timeout in seconds.
func WithTrustEnv ¶
WithTrustEnv controls whether http_proxy/https_proxy environment variables are honoured when no explicit proxy is configured.
type Params ¶
type Params []Param
Params is an ordered query parameter list. Use Param to preserve duplicates.
type Request ¶
type Request struct {
// Method is the HTTP method. Empty means GET.
Method string
// URL is the target. A URL without a scheme defaults to https.
URL string
// Headers accepts anything the WithHeaders option accepts, including
// []string{"Name: Value"} and map[string]string.
Headers HeaderTypes
// Params accepts anything the WithParams option accepts.
Params any
// Cookies accepts anything the WithCookies option accepts.
Cookies CookieTypes
// Body is the raw request body. JSON wins when both are set.
Body []byte
// JSON is marshalled as the request body and sets application/json.
JSON any
// Browser loads the URL in the full browser instead of the fast client:
// scripts run, the page settles, and the response body is the document as
// it ended up. It needs the browser package linked in, which importing the
// module root does; a program that imports requests alone is told so.
//
// Only a GET of a URL has a browser path, and it is slower by orders of
// magnitude, so leave it off unless the page needs scripts.
Browser bool
// Impersonate selects the fingerprint target, for example
// impersonate.Chrome131. Empty uses the session default.
Impersonate string
// Timeout overrides the session timeout when it is non-zero.
Timeout time.Duration
// Proxy overrides the session proxy when it is non-empty.
Proxy string
}
Request describes an HTTP request as a value. It is what Response.Request reports for a request that was sent, and what Session.Send accepts to send one, so a request can be built, stored and passed around rather than being a list of options at the call site.
Only Method and URL are required; every other field falls back to the session's setting when it is left at its zero value.
func ToRequest ¶
func ToRequest(v RequestTypes) (Request, error)
ToRequest turns an accepted request input - a Request, a *Request or a URL string - into a Request. It is what Send, Browse and the method helpers run their input through, exported for a caller that needs the value: the browser package opens the page object behind the same input.
type RequestException ¶
RequestException is the base error for the requests package. It carries an optional associated *Response and a curl-like numeric code for parity with curl_cffi.
func (*RequestException) Error ¶
func (e *RequestException) Error() string
func (*RequestException) Unwrap ¶
func (e *RequestException) Unwrap() error
type RequestTypes ¶
type RequestTypes interface{}
RequestTypes is the set of accepted request inputs: a Request value, a *Request, or a URL string, which means a GET with the session's defaults.
It exists so the common case needs no literal - Send(url) and Browse(url) are one word each - while a request that sets several fields is still written as one. The other inputs in this package take several shapes the same way: HeaderTypes, CookieTypes and Params.
type Response ¶
type Response struct {
URL string
Content []byte
StatusCode int
Reason string
Ok bool
Headers *Headers
Cookies *Cookies
Elapsed time.Duration
DefaultEncoding string
RedirectCount int
RedirectURL string
HTTPVersion int
PrimaryIP string
PrimaryPort int
LocalIP string
LocalPort int
History []*Response
Request *Request
DownloadSize int64
UploadSize int64
HeaderSize int64
RequestSize int64
// Body is set when the request used Stream=true. It must be closed by the
// caller (or via Close).
Body io.ReadCloser
// contains filtered or unexported fields
}
Response holds everything the server sent back, mirroring curl_cffi.requests.Response.
func Browse ¶
func Browse(req RequestTypes, opts ...Option) (*Response, error)
Browse loads a request in the browser in a throwaway session, spelled like Send with the path in the name. It needs the browser package imported, which is what installs it:
rsp, err := Browse("https://quotes.toscrape.com/js/")
func Do ¶
Do sends a request in a throwaway session, mirroring curl_cffi's module-level requests.request helper.
func Send ¶
func Send(req RequestTypes, opts ...Option) (*Response, error)
Send performs req in a throwaway session, so a Request built as a value can be sent without a Session of its own:
rsp, err := Send(Request{
Method: "GET",
URL: "https://httpbun.com/get",
Impersonate: Chrome146,
})
It reads the whole body before returning, like the other helpers here. Use Session.Send instead when cookies and connections should be reused across requests.
func (*Response) CharsetEncoding ¶
CharsetEncoding returns the charset from the Content-Type header, if any.
func (*Response) ContentType ¶
ContentType returns the Content-Type header value.
func (*Response) IsRedirect ¶
IsRedirect reports whether this is a well-formed redirect response.
func (*Response) IterContent ¶
IterContent yields the response body in chunks. In non-stream mode it yields the buffered content once. In stream mode it reads from the network.
func (*Response) RaiseForStatus ¶
RaiseForStatus returns an *HTTPError if the response status is not in [200, 400), matching requests/curl_cffi.
func (*Response) SetEncoding ¶
SetEncoding overrides the decode charset. It must be called before Text.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is a requests-like client with a shared cookie jar and connection pool. It is safe for concurrent use.
func NewSession ¶
NewSession creates a Session. Options set here become defaults for every request and can be overridden per request.
func (*Session) Browse ¶
func (s *Session) Browse(req RequestTypes, opts ...Option) (*Response, error)
Browse loads a request in the browser, which is Send with Browser set: the name says which path it takes, so the two read alike:
sess.Send("https://example.com/") // impersonated HTTP
sess.Browse("https://example.com/") // the same URL, rendered
It takes anything Send does, and Get with WithBrowser reaches the same page.
func (*Session) Close ¶
func (s *Session) Close()
Close releases idle connections held by the session.
func (*Session) Headers ¶
Headers returns the session default headers. Mutating it affects subsequent requests.
func (*Session) Send ¶
func (s *Session) Send(req RequestTypes, opts ...Option) (*Response, error)
Send performs the request described by req. It is the struct-shaped counterpart to Request(method, url, opts...): the same request can be built as a value, stored, or filled in from configuration, instead of being spread across options at the call site.
req := requests.Request{
Method: "GET",
URL: "https://httpbun.com/get",
Headers: []string{"Accept: application/json"},
Impersonate: impersonate.Chrome131,
}
resp, err := sess.Send(req)
Fields left at their zero value fall back to the session's defaults, so an empty Method means GET and an empty Timeout means the session timeout.
func (*Session) SetCookies ¶
func (s *Session) SetCookies(c CookieTypes)
SetCookies replaces the session cookie jar.
func (*Session) UserAgent ¶
UserAgent reports the User-Agent this session sends: the impersonated browser's, when a preset is selected, and the curl default otherwise. A caller that also exposes a user agent to page scripts uses this so that what the server is told and what navigator.userAgent reports are the same browser, rather than one desktop Chrome to the server and another to the page.
type SessionClosed ¶
type SessionClosed struct{ *RequestException }
SessionClosed indicates the session was already closed.
type TooManyRedirects ¶
type TooManyRedirects struct{ *RequestException }
TooManyRedirects indicates the redirect limit was exceeded.
type UnrewindableBodyError ¶
type UnrewindableBodyError struct{ *RequestException }
UnrewindableBodyError indicates the body could not be replayed for a redirect or retry.
type UnsupportedOptionError ¶
type UnsupportedOptionError struct{ *RequestException }
UnsupportedOptionError indicates an option that curl_cffi accepts but that this port cannot honour. It is returned rather than ignored on purpose: silently dropping a fingerprint option would send a request that does not match what the caller asked for, which is worse than failing outright.