Skip to content

About

Official Go client for the URLpipe API: Markdown, screenshots, metadata, Lighthouse and more from any URL, rendered in real Chrome. Standard library only.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

urlpipe-go

Turn any URL into clean data from Go: Markdown, rendered HTML, a full-page screenshot, a PDF, metadata, a summary, keywords, data in a schema you define, console errors, a Lighthouse audit or the technologies it is built with, each page rendered in real Chrome.

This is the official Go client for URLpipe. It uses the standard library only, and the repository also ships urlpipe, a command-line tool built on it.

Install

go get github.com/URLpipe/urlpipe-go

Requires Go 1.21 or later.

Quickstart

Grab a project API key from your dashboard and put it in URLPIPE_API_KEY. The Free plan gives you 1,000 credits a month, no card needed.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/URLpipe/urlpipe-go"
)

func main() {
	client, err := urlpipe.NewClient() // reads URLPIPE_API_KEY
	if err != nil {
		log.Fatal(err)
	}

	res, err := client.Markdown(context.Background(), "https://example.com", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Data)
}

Every call waits for the result and hands it back typed. The API itself defaults to async; the client sends sync: true for you, because a library caller almost always wants the answer. See Async and Wait to opt out.

The client

client, err := urlpipe.NewClient(
	urlpipe.WithAPIKey("..."),              // default: $URLPIPE_API_KEY
	urlpipe.WithBaseURL("https://urlpipe.dev"),
	urlpipe.WithTimeout(90*time.Second),    // per HTTP request
	urlpipe.WithMaxRetries(2),              // transient failures
	urlpipe.WithWaitTimeout(5*time.Minute), // how long a long analysis is polled for
	urlpipe.WithHTTPClient(&http.Client{}), // your own transport
)

NewClient returns urlpipe.ErrMissingAPIKey when there is no key. A *Client is safe to share between goroutines.

Methods

Every method takes a context.Context first and the URL second, and returns a *urlpipe.Response[T]:

type Response[T any] struct {
	Status Status            // "completed", "accepted" or "processing"
	Data   T                 // the typed result, set when Status is "completed"
	Token  string            // fetch the result again for free, for 30 days
	Labels map[string]string // the labels the request was made with
	Meta   Meta              // cache, credits, timing: see below
}
ctx := context.Background()

md, _ := client.Markdown(ctx, url, nil)     // Data: string
html, _ := client.HTML(ctx, url, nil)       // Data: string, the HTML after JavaScript ran
sum, _ := client.Summarize(ctx, url, nil)   // Data: string, Markdown
meta, _ := client.Meta(ctx, url, nil)       // Data: *urlpipe.Metadata
kw, _ := client.Keywords(ctx, url, nil)     // Data: []string
logs, _ := client.Console(ctx, url, nil)    // Data: []urlpipe.ConsoleEntry
tech, _ := client.Technologies(ctx, url, nil) // Data: *urlpipe.Technologies

fmt.Println(meta.Data.Title, meta.Data.Language, meta.Data.PublishedAt)
if meta.Data.Image != nil {
	fmt.Println(meta.Data.Image.URL, meta.Data.Image.Width, meta.Data.Image.Height)
}
for _, e := range logs.Data {
	fmt.Println(e.Type, e.Text) // "error", "warning" or "exception"
}

Screenshot

The image arrives decoded, with its format read off the bytes and a link that needs no API key:

shot, err := client.Screenshot(ctx, "https://example.com", &urlpipe.ScreenshotOptions{
	Screenshot: map[string]any{"format": "webp", "viewport_width": 390, "device_scale_factor": 2},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(shot.Data.MIMEType)  // image/webp
fmt.Println(shot.Data.ResultURL) // put it straight in an <img>
err = shot.Data.Save("example.webp")

PDF

The whole rendered page, printed after it is scrolled through so its lazy images are in:

pdf, err := client.PDF(ctx, "https://example.com/invoice", &urlpipe.PDFOptions{
	PDF: map[string]any{"paper_size": "letter", "landscape": true},
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(pdf.Data.ResultURL) // a link that needs no API key
err = pdf.Data.Save("invoice.pdf")

Extract: data in a schema you define

Name the fields you want and the result has exactly those keys, in that order, null where the page gives no value:

res, err := client.Extract(ctx, "https://example.com/products/trail-shoe",
	[]urlpipe.Field{
		{Name: "name", Type: "string"},
		{Name: "price", Type: "number", Description: "The current price, without the currency"},
		{Name: "in_stock", Type: "boolean"},
		{Name: "sizes", Type: "array", Items: "string"},
	},
	&urlpipe.ExtractOptions{Instructions: "Ignore the related products."})
if err != nil {
	log.Fatal(err)
}

var product struct {
	Name    string   `json:"name"`
	Price   *float64 `json:"price"`
	InStock *bool    `json:"in_stock"`
	Sizes   []string `json:"sizes"`
}
err = res.Data.Decode(&product)
// res.Data.Values holds the same as a map, res.Data.Keys the fields in order.

A field's Type is string, number, integer, boolean, date, datetime, url, email, object (with its own Fields) or array (with Items: a type name, or a Field without a Name).

Lighthouse

audit, err := client.Lighthouse(ctx, "https://example.com", &urlpipe.LighthouseOptions{
	Device:        "desktop", // default "mobile"
	IncludeAudits: true,      // add all 150+ audits
})
fmt.Println(*audit.Data.Categories["performance"].Score)
fmt.Println(audit.Data.Metrics["largest-contentful-paint"].DisplayValue)
// audit.Data.Raw holds the whole JSON for anything else.

Scrape: several results off one page visit

res, err := client.Scrape(ctx, "https://example.com",
	[]urlpipe.Operation{urlpipe.OperationMarkdown, urlpipe.OperationMeta, urlpipe.OperationScreenshot},
	nil)
if err != nil {
	log.Fatal(err)
}
md, err := res.Data.Markdown()
meta, err := res.Data.Meta()
shot, err := res.Data.Screenshot() // decoded, like Client.Screenshot

ScrapeOptions carries each operation's own settings: Screenshot, PDF, Fields and Instructions for an extract, Device and IncludeAudits for an audit. res.Data.PDF() and res.Data.Extract() read those two.

res.Data.Order lists the operations in the order you asked for them. Operations fail independently. An accessor returns a *urlpipe.OperationError for an operation that failed; its Pending() is true for a Lighthouse audit that was still running (fetch the scrape again with client.Result(ctx, res.Token, urlpipe.OperationScrape)). When every operation fails, Scrape returns an *urlpipe.AnalysisFailedError whose Scrape field holds each operation's error.

Options

Every method takes an options struct; nil means the defaults, and only the fields you set are sent.

res, err := client.Markdown(ctx, url, &urlpipe.Options{
	MaxAge:         urlpipe.MaxAgeString("3 days"), // or MaxAgeSeconds(3600), MaxAgeDuration(time.Hour)
	Labels:         map[string]string{"client": "acme"},
	Residential:    true,
	PageOptions:    map[string]any{"block_ads": true, "block_cookie_banners": true, "block_popups": true, "remove_selectors": []string{".related"}},
	IdempotencyKey: "order-1234",
	Extra:          map[string]any{"some_new_param": true}, // merged into the body as-is
})

ScreenshotOptions, PDFOptions, ExtractOptions, LighthouseOptions and ScrapeOptions embed Options and add their own fields. Cached results are free: MaxAgeSeconds(0) forces a fresh analysis, and a wider MaxAge lowers your bill.

Meta

res.Meta is what the response headers said. A header the API did not send is nil (or ""), never a panic.

m := res.Meta
m.Cache              // "hit", "miss" or "partial"
m.CacheAge           // *int seconds, on a hit
m.ProcessingTimeMs   // *int
m.Quota.Cost         // *int credits this call spent
m.Quota.Remaining    // *Amount: .Value, or .Unlimited on an unlimited plan
m.Quota.Overage      // *int
m.Quota.ResetsAt     // *time.Time
m.ConcurrencyLimit   // *Amount: size your worker pool from it
m.FinalURL           // where the page ended up, after its redirects
m.IdempotentReplayed // true when an Idempotency-Key replayed an earlier answer

Async and Wait

Set Async: true to get a token back at once and collect the result later, from a webhook or with Wait:

accepted, err := client.Lighthouse(ctx, url, &urlpipe.LighthouseOptions{
	Options: urlpipe.Options{Async: true, ReportTo: "https://example.com/webhooks/urlpipe"},
})
// accepted.Status == urlpipe.StatusAccepted, accepted.Token is set

res, err := client.Wait(ctx, accepted.Token, urlpipe.OperationLighthouse, &urlpipe.WaitOptions{
	Timeout: 5 * time.Minute, Interval: 2 * time.Second,
})
audit := res.Data.(*urlpipe.Lighthouse)

GET /result/:token does not say which operation made a token, so Result and Wait take the operation as a hint and type Data as that operation's method would. Pass "" and a JSON result decodes into any while a text result stays a string, so a screenshot or a PDF stays Base64: use client.Wait(ctx, token, urlpipe.OperationScreenshot, nil) to get a decoded *Screenshot, and urlpipe.OperationPDF for a *PDF.

client.Result(ctx, token, op) is a single fetch: a finished result comes back with StatusCompleted, one still running with StatusProcessing and no error.

You rarely need Wait for sync calls. The API holds a sync request for 60 seconds; when an analysis takes longer, the client polls for the result every 2 seconds for up to the wait timeout, so you still see one call that returned the result. If the wait runs out, the error matches urlpipe.ErrWaitTimeout and carries the token to collect it later.

Webhooks

VerifyWebhook checks a signed delivery and returns its payload. It needs no client:

http.HandleFunc("/webhooks/urlpipe", func(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "unreadable body", http.StatusBadRequest)
		return
	}
	event, err := urlpipe.VerifyWebhook(body, r.Header, os.Getenv("URLPIPE_WEBHOOK_SECRET"), 5*time.Minute)
	if err != nil {
		http.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}
	data, _ := event.Data() // typed by event.Operation: string, *Screenshot, *Metadata, ...
	log.Println(event.Token, event.Success, data)
	w.WriteHeader(http.StatusNoContent)
})

Give it the raw request body, the exact bytes received. Decoding the JSON and encoding it again changes the bytes, and the signature no longer matches. It accepts a delivery when any v1= signature matches (so a secret rotation verifies with either secret), ignores other schemes, and refuses a timestamp further than the tolerance from now (zero means 5 minutes). A refusal is a *urlpipe.WebhookVerificationError with a Reason. Holding the two header values instead of an http.Header? Use VerifyWebhookSignature(body, timestamp, signature, secret, tolerance).

Errors

Every API and transport error is an *urlpipe.Error with Kind, Status, Code, Message, Body and Token. Test for a kind with errors.Is, and reach the extra fields with errors.As:

_, err := client.Summarize(ctx, url, nil)

var quota *urlpipe.QuotaExceededError
var apiErr *urlpipe.Error
switch {
case errors.As(err, &quota):
	fmt.Printf("needs %d credits; the allowance resets %s\n", quota.Needed, quota.ResetsAt)
case errors.Is(err, urlpipe.ErrAnalysisFailed):
	fmt.Println("the page could not be analysed:", err)
case errors.As(err, &apiErr):
	fmt.Println(apiErr.Kind, apiErr.Status, apiErr.Code, apiErr.Message)
}
Sentinel When Detailed type
ErrAuthentication 401: the key is missing or not active
ErrEmailUnverified 403: confirm the email on the account
ErrInvalidRequest 422 with a code: invalid_url, invalid_options, ...
ErrAnalysisFailed 422: the page could not be analysed; the message says why *AnalysisFailedError (Scrape)
ErrQuotaExceeded 429: the Free plan's credits are spent *QuotaExceededError (Limit, Used, Needed, ResetsAt, NextPlan, UpgradeURL)
ErrConcurrencyLimit 429: every parallel request is running *ConcurrencyLimitError (Limit, Running, NextPlan, UpgradeURL)
ErrRateLimited 429: sending too fast *RateLimitedError (RetryAfter)
ErrNotFound 404: no result for this token
ErrStaleResult 410: the result is past its 30 days
ErrServer 5xx
ErrConnection the API could not be reached (Unwrap gives the cause)
ErrWaitTimeout the analysis was still running when the wait ended (Token)

Any other answer, such as a 403 other than email_unverified or a 429 with an unknown code, is a plain *urlpipe.Error with Kind urlpipe.KindUnexpected. Code is set only when the body's error is a code like invalid_url; when it is a sentence, the sentence is in Message. When every operation of a scrape fails, Message reads Every operation failed: <op>: <error>; ....

NextPlan is the plan above the account's current one (Name, MonthlyPriceCents, MonthlyCredits, MaxConcurrentRequests) and UpgradeURL the page to move to it; on the highest plan NextPlan is nil and UpgradeURL empty.

errors.As(err, &apiErr) also works on the detailed types. A cancelled context comes back as the context's own error.

Retries and idempotency

Connection errors, 500/502/503 and concurrency_limit are retried after 1 s, 2 s, 4 s, ... (at most 60 s); rate_limited after the Retry-After it names (else 1 s, at most 60 s). That happens up to WithMaxRetries times (default 2). A 401, 403, 404, 410, 422, 504, quota_exceeded or any other 429 is never retried.

A retry is only safe if it cannot run the work twice, so every analysis the client might retry carries an Idempotency-Key: yours from Options.IdempotencyKey, or a UUID the client generates for that call and reuses for each of its retries. The API answers a repeated key with the first request's token and result, charged once and delivered to your webhook once. WithMaxRetries(0) turns retries off, and the generated key with them.

Command-line tool

The same repository ships urlpipe, a command-line tool built on this package, for the terminal and for scripts.

brew install urlpipe/tap/urlpipe                     # macOS and Linux
scoop bucket add urlpipe https://github.com/URLpipe/scoop-bucket
scoop install urlpipe                                # Windows
go install github.com/URLpipe/urlpipe-go/cmd/urlpipe@latest

Or download a binary for your system from Releases. Then save your key once:

urlpipe login        # or set URLPIPE_API_KEY, or pass --api-key

Results go to stdout and everything else to stderr, so they pipe cleanly:

urlpipe markdown example.com > page.md
urlpipe html https://example.com | grep -c "<a "
urlpipe screenshot https://example.com --width 390 --scale 2 -o mobile.png
urlpipe screenshot example.com --dark --viewport-only        # writes example.com.png
urlpipe pdf https://example.com/invoice --paper letter -o invoice.pdf
urlpipe meta example.com | jq .title
urlpipe extract example.com/products/trail-shoe --field name:string --field price:number | jq .price
urlpipe keywords example.com --json
urlpipe technologies example.com                           # one technology per line, with its version
urlpipe summarize https://example.com/post
urlpipe scrape example.com --ops markdown,meta,console
urlpipe markdown example.com --async                          # prints a token
urlpipe result TOKEN --op markdown --wait

Every analysis command takes --max-age, --label key=value, --residential, --async, --block-ads, --block-cookie-banners, --block-popups, --scroll-to-bottom, --wait-for CSS, --timeout and -v (print the cache status, cost and credits left). urlpipe help <command> lists a command's own flags.

In CI

Two commands can fail a build on what they find, with exit code 3:

urlpipe console "$PREVIEW_URL" --fail-on-errors            # any console error or uncaught exception
urlpipe lighthouse "$PREVIEW_URL" --device mobile --min-score 90
Exit code Meaning
0 Success
1 The API or the network failed
2 The command line is wrong, or there is no API key
3 --fail-on-errors or --min-score found a problem
4 urlpipe result: the analysis is still running (add --wait)

Links

License

MIT, see LICENSE.

About

Official Go client for the URLpipe API: Markdown, screenshots, metadata, Lighthouse and more from any URL, rendered in real Chrome. Standard library only.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages