// Package fetch downloads product pages with a browser-like TLS and HTTP/2 // fingerprint and tells real pages apart from bot checks. package fetch import ( "context" "errors" "fmt" "io" stdhttp "net/http" "net/url" "time" http "github.com/bogdanfinn/fhttp" tlsclient "github.com/bogdanfinn/tls-client" ) const ( DefaultTimeout = 30 * time.Second DefaultMaxBody = 16 << 20 ) // ErrBodyTooLarge is returned when a response exceeds Options.MaxBody. var ErrBodyTooLarge = errors.New("response body too large") type Options struct { // Browser to impersonate. Defaults to DefaultBrowser(). Browser *Browser // Jar holds the cookies. Defaults to a new, empty jar. Jar *Jar // Timeout per request, including redirects. Defaults to DefaultTimeout. Timeout time.Duration // MaxBody is the largest body read, after decompression. Defaults to // DefaultMaxBody. MaxBody int64 } // Client fetches pages. It is safe for concurrent use. type Client struct { http tlsclient.HttpClient browser Browser jar *Jar maxBody int64 } // Response is a fetched page. type Response struct { URL string // as requested FinalURL string // after redirects Status int Header stdhttp.Header Body []byte Verdict Verdict // Challenge names the bot check found, such as "cloudflare", when // Verdict is Challenge. Challenge string Elapsed time.Duration } func New(opts Options) (*Client, error) { browser := DefaultBrowser() if opts.Browser != nil { browser = *opts.Browser } if opts.Jar == nil { opts.Jar = NewJar() } if opts.Timeout == 0 { opts.Timeout = DefaultTimeout } if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody } hc, err := tlsclient.NewHttpClient(nil, tlsclient.WithClientProfile(browser.Profile), tlsclient.WithRandomTLSExtensionOrder(), tlsclient.WithCookieJar(opts.Jar), tlsclient.WithTimeoutMilliseconds(int(opts.Timeout/time.Millisecond)), ) if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) } return &Client{http: hc, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil } // Jar returns the client's cookie jar. func (c *Client) Jar() *Jar { return c.jar } // Get fetches rawURL the way Chrome opens a bookmark. A response with a bad // status is not an error: check Verdict. func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) { u, err := url.Parse(rawURL) if err != nil { return nil, err } if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return nil, err } req.Header = c.browser.navigationHeaders(u) start := time.Now() resp, err := c.http.Do(req) if err != nil { return nil, err } // fhttp's decompressing readers close the raw body with them. body := resp.Body if !resp.Uncompressed && resp.Header.Get("Content-Encoding") != "" { body = http.DecompressBody(resp) } defer func() { _ = body.Close() }() data, err := io.ReadAll(io.LimitReader(body, c.maxBody+1)) if err != nil { return nil, fmt.Errorf("reading body: %w", err) } if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) } r := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data) r.Elapsed = time.Since(start) return r, nil } // NewResponse builds and classifies a Response for a page obtained another // way, such as a saved fixture or the browser fallback. func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response { if header == nil { header = stdhttp.Header{} } r := &Response{ URL: rawURL, FinalURL: finalURL, Status: status, Header: header, Body: body, } r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body) return r }