fetch

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 39 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fetch reads one public web page per call: public addresses only, no crawling, no cookies. By default a client with a Chrome TLS fingerprint goes first, with a plain Go client as backup for its library's own TLS or protocol errors; robots.txt is consulted only when asked.

Index

Constants

View Source
const (
	ClientChromeLike  = "chrome_like"
	ClientPlain       = "plain"        // the plain client as the first step (Impersonate off or fallback)
	ClientPlainBackup = "plain_backup" // the plain client after the Chrome-like client errored or was refused
	ClientStructured  = "structured"   // a JavaScript-only page's structured data, when nothing else read it
)

Clients, the steps of the ladder that produced an attempt.

View Source
const (
	OutcomeOK         = "ok"
	OutcomeRefused    = "refused"    // HTTP 403 or 429
	OutcomeChallenge  = "challenge"  // HTTP 503 or a bot-challenge page, even on a 403 (Cloudflare's is)
	OutcomeNeedsJS    = "needs_js"   // an HTML shell whose content only JavaScript would render
	OutcomeTimeout    = "timeout"    // the client's time budget ran out
	OutcomeError      = "error"      // network error, other HTTP status, address refusal
	OutcomeDisallowed = "disallowed" // robots.txt, only with RespectRobots
)

Outcomes of one attempt.

View Source
const (
	ImpersonateAlways   = "always"   // Chrome-like first, plain backup on its TLS or protocol errors or a refusal (default)
	ImpersonateFallback = "fallback" // plain first, Chrome-like when the plain client is refused or challenged
	ImpersonateOff      = "off"      // plain client only
)

Impersonation modes.

View Source
const (
	DefaultUserAgent   = "refetch"
	DefaultRobotsAgent = "refetch"
	DefaultTimeout     = 20 * time.Second
	MaxBytes           = 2 << 20
	TypeMarkdown       = "text/markdown; charset=utf-8" // the content type of a document read as Markdown

)

Defaults for the zero Fetcher.

View Source
const MaxDocBytes = 32 << 20

MaxDocBytes caps a PDF or office file, which runs larger than a page.

View Source
const StructuredLabel = "(From the page's structured data: schema.org JSON-LD that sites publish for search engines.)"

StructuredLabel heads Markdown read from a page's structured data.

Variables

View Source
var ErrDocument = errors.New("could not read the document")

ErrDocument is a PDF or office file that could not be turned into text.

View Source
var ErrNotText = errors.New("not a web page or text")

ErrNotText is a page that is a file, such as a PDF or an image, rather than HTML or text.

Functions

func Blocked

func Blocked(status int, body []byte) bool

Blocked reports an anti-bot refusal: HTTP 403 or 429, or a challenge.

func Challenge

func Challenge(status int, body []byte) bool

Challenge reports whether a response is a bot challenge rather than the page: HTTP 503, HTTP 202 (AWS WAF answers a GET with an empty 202 and a challenge script), or a page with little text carrying a challenge marker: bot managers inject their scripts into real pages too (The Atlantic's articles load /cdn-cgi/challenge-platform/scripts/).

func ChromeBrands added in v0.3.0

func ChromeBrands(major int) [3][2]string

ChromeBrands are the brands and major versions Chrome of a major version names in its client hints, in its order. Chromium derives the GREASE brand, the brand's version and the order of the three from the major version, so a list from another version gives a client away.

func Clip

func Clip(s string, n int) string

Clip cuts s to n runes, marking the cut.

func DialContext

func DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext dials the way both clients do: public addresses only, checked after DNS resolution, or through the proxy UseProxy set. The headless Chrome step's proxy dials with it.

func Document added in v0.3.0

func Document(ctx context.Context, body []byte) (md string, ok bool, err error)

Document returns a PDF, Word, Excel or PowerPoint file as Markdown, found by its bytes, not its name or type. ok is false for any other file; err is set for a document that could not be read, wrapping ErrDocument.

func EmptyRendered

func EmptyRendered(dom []byte) bool

EmptyRendered reports a headless Chrome DOM with under 20 characters of text, or under 200 in over 100 KB of markup; scripts and mount points stay.

func FullMarkdown added in v0.3.0

func FullMarkdown(body []byte, contentType string, page *url.URL) string

FullMarkdown is Markdown with the site's navigation, footers and sidebars kept.

func IsWebURL added in v0.3.0

func IsWebURL(raw string) bool

IsWebURL reports whether raw is an http or https URL with a host, the only kind refetch reads.

func IsolatePDF added in v0.3.0

func IsolatePDF(name string, args ...string)

IsolatePDF reads every PDF in a child process, name run with args, that runs ServePDF. The parser recurses without end on some malformed files, a stack overflow that no recover catches; in a child it ends only the child, and a timeout kills the parse instead of leaving it to run.

func LoginForm added in v0.4.0

func LoginForm(body []byte, contentType string) bool

LoginForm reports a short HTML page with a visible password input.

func Markdown added in v0.2.0

func Markdown(body []byte, contentType string, page *url.URL) string

Markdown returns an HTML page as Markdown: headings, lists, links, tables and code blocks kept; scripts, styles, hidden elements and the site's navigation, banners, footers, sidebars and cookie notices dropped. When that leaves next to nothing, the page was not laid out the way the trimming expects, and the whole page comes back. Links resolve against page (a <base href> wins); only http, https and mailto links keep their target. Other types come back as Text returns them.

func NeedsJS

func NeedsJS(body []byte, contentType string) bool

NeedsJS reports a JavaScript-only shell: under 200 characters of text plus an empty mount point, an enable-JavaScript notice or over 100 KB of markup, or under 100 characters plus a script (a proof-of-work page too).

func NotFound added in v0.4.0

func NotFound(body []byte, contentType string) bool

NotFound reports a short HTML page whose title or an h1 or h2 heading says the page does not exist: a soft 404 served with HTTP 200.

func NotText added in v0.2.0

func NotText(contentType string, body []byte) string

NotText is the media type of a body that is not text, or "" for text. The body decides when the server named no type, or named a text type over PDF bytes.

func Paywall added in v0.4.0

func Paywall(body []byte, contentType string, textChars int) bool

Paywall reports an HTML page whose article is for subscribers: its schema.org data marks the article not free, or the page gives under paywallChars of text (textChars, as read) and shows a paywall. A page marked not free can still give the whole article.

func Rewrite added in v0.3.0

func Rewrite(rawURL string) string

Rewrite returns the address that serves a page's content directly, or "" when rawURL is read as is. Google Docs, Sheets and Slides editors are JavaScript apps whose HTML holds no document text, and a Drive file's page is a viewer: their export addresses return the document itself, for anyone the document is shared with.

func ServePDF added in v0.3.0

func ServePDF(ctx context.Context, in io.Reader, out, errOut io.Writer) int

ServePDF is the child side of IsolatePDF: it reads a PDF from in and writes its text to out, or why it could not to errOut and returns 1.

func Structured added in v0.3.0

func Structured(body []byte, page *url.URL) string

Structured is the Markdown of the posts a page describes in its schema.org JSON-LD: a question with its answers (QAPage), a forum post with its comments, or an article's body. Q&A and forum sites publish the full text there for search engines, also when the page itself is an app shell or a login wall. It is "" when the data holds under 200 characters of text, as many sites give only a teaser.

func Text

func Text(body []byte, contentType string) string

Text returns readable text: HTML without scripts, styles and tags; other types as is. When a page's <noscript> elements, where some apps put the whole page for browsers without JavaScript, hold over twice the text it shows, their text is added.

func UseProxy added in v0.2.0

func UseProxy() string

UseProxy sends every connection through the proxy in HTTPS_PROXY (or HTTP_PROXY) as a CONNECT tunnel, except to hosts NO_PROXY lists. TLS runs inside the tunnel, so the site still sees refetch's own handshake. It returns the proxy's address, or "" (and dials directly) when none is set.

Types

type Attempt

type Attempt struct {
	URL, Host, Client, Outcome string
	Status                     int
	Bytes                      int
	Duration                   time.Duration
	Err                        string
}

Attempt is one client's try at a page, reported to Fetcher.Record.

type Fetcher

type Fetcher struct {
	Impersonate   string        // ImpersonateAlways when empty
	RespectRobots bool          // consult robots.txt before fetching
	UserAgent     string        // the plain client's User-Agent; DefaultUserAgent when empty
	RobotsAgent   string        // the robots.txt agent name; DefaultRobotsAgent when empty
	Timeout       time.Duration // per client; DefaultTimeout when zero
	RawFiles      bool          // return a file that is neither text nor a document, such as an image, as its bytes, up to MaxDocBytes, instead of ErrNotText
	Record        func(Attempt) // called after every attempt, if set
	// contains filtered or unexported fields
}

Fetcher gets pages. The zero value impersonates Chrome first and ignores robots.txt.

func (*Fetcher) Get

func (f *Fetcher) Get(ctx context.Context, rawURL string) (Page, error)

Get fetches rawURL, walking the clients the impersonation mode allows. The error names why the page could not be read.

type Page

type Page struct {
	Body        []byte
	ContentType string
	URL         string    // where Body came from, after redirects; "" when unknown
	Last        Attempt   // the attempt that produced Body, or the last failure
	Attempts    []Attempt // every attempt of this call, in order
	Via         string    // where the text came from when not the page itself, such as a site's API
	Shell       []byte    // a JavaScript-only page as the HTTP clients got it, kept for its structured data
	ErrorBody   []byte    // the body of the last answer with an HTTP error status, where an API says why
}

Page is a fetched page, or the attempts that failed to fetch it.

Jump to

Keyboard shortcuts

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