Skip to main content

Confirm

Are you sure?

Go · Code recipe

Take a screenshot of a website in Go

Save a full-page PNG of any website, in Go 1.21+ with net/http from the standard library. Every program on this page runs as it stands — each one was run against a stub of the API before it was published.

By · Last updated: September 2026

TL;DR

To take a screenshot of a website in Go, POST its URL to https://urlpipe.dev/screenshot with sync set to true, decode the Base64 body with base64.StdEncoding.DecodeString and write the bytes to a .png file. It is a full-page capture from real Chrome for 1 credit; leave sync out and the result goes to your webhook instead.

Free plan, no credit card. 1,000 credits a month.

One POST to /screenshot loads the page in real Chrome, scrolls it top to bottom so lazy images load, and captures the whole document — not just the fold. The image comes back Base64-encoded in a text/plain body, so the Go work is two lines: decode it with base64.StdEncoding.DecodeString and write the bytes.

The request below also sets page_options.block_cookie_banners, because a consent dialog over the page is the most common reason a screenshot is useless. Every other knob — viewport, device scale, JPEG or WebP, one element by selector, dark mode — goes in screenshot_options.

Setup

Before you start

Nothing to fetch: every import is standard library, so each program runs with go run as a single file. Put your API key in the environment.

Terminal
go version   # go1.21 or later
export URLPIPE_API_KEY="your_api_key"

The request

Save a screenshot as a PNG file

"sync": true keeps the request open until the result is ready. http.Client has no timeout unless you set one, and res.Body is a stream: io.ReadAll turns it into bytes, and defer res.Body.Close() hands the connection back. The body is Base64 text; base64.StdEncoding.DecodeString gives the bytes back.

main.go
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload, err := json.Marshal(map[string]any{
		"url":          "https://example.com",
		"page_options": map[string]any{"block_cookie_banners": true},
		"sync":         true,
	})
	if err != nil {
		log.Fatal(err)
	}

	req, err := http.NewRequest(http.MethodPost, "https://urlpipe.dev/screenshot", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("URLPIPE_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	// A sync call can take up to 60 s; the zero-value client would wait forever.
	client := &http.Client{Timeout: 90 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	// The body is the result or the error, so read all of it first.
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	if res.StatusCode != http.StatusOK {
		log.Fatalf("URLpipe answered %d: %s", res.StatusCode, body)
	}

	png, err := base64.StdEncoding.DecodeString(string(body))
	if err != nil {
		log.Fatal(err)
	}
	if err := os.WriteFile("screenshot.png", png, 0o644); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Saved screenshot.png (%d bytes)\n", len(png))
}

Run it: go run main.go

Async

The async variant: a token, a webhook and a poll

Leave out sync and the answer is a token, straight away. Decode only the field you need into an anonymous struct; switch on the status covers the four answers GET /result/:token can give.

main.go
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

const api = "https://urlpipe.dev"

var client = &http.Client{Timeout: 30 * time.Second}

// send makes one request to the API and returns the status and the body.
func send(method, path string, payload any) (int, []byte) {
	var reader io.Reader
	if payload != nil {
		data, err := json.Marshal(payload)
		if err != nil {
			log.Fatal(err)
		}
		reader = bytes.NewReader(data)
	}
	req, err := http.NewRequest(method, api+path, reader)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("URLPIPE_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	return res.StatusCode, body
}

// poll collects a result by token. The result is POSTed to report_to when it is
// ready; polling is the other way to collect it, and a backup for the webhook.
func poll(token string) []byte {
	for attempt := 0; attempt < 60; attempt++ {
		status, body := send(http.MethodGet, "/result/"+token, nil)
		switch status {
		case http.StatusOK:
			return body
		case http.StatusAccepted: // still processing
			time.Sleep(2 * time.Second)
		case http.StatusUnprocessableEntity:
			log.Fatalf("The analysis failed: %s", body)
		case http.StatusGone:
			log.Fatal("The result is past the 30-day window; send the request again.")
		default:
			log.Fatalf("URLpipe answered %d: %s", status, body)
		}
	}
	log.Fatal("Still processing after two minutes; try the token again later.")
	return nil
}

func main() {
	// No "sync": the request is accepted at once and the work carries on without you.
	status, body := send(http.MethodPost, "/screenshot", map[string]any{
		"url":          "https://example.com",
		"page_options": map[string]any{"block_cookie_banners": true},
		"report_to":    "https://your-app.com/webhooks/urlpipe",
		"labels":       map[string]any{"customer": "acme"},
	})
	if status != http.StatusOK {
		log.Fatalf("URLpipe answered %d: %s", status, body)
	}
	var accepted struct {
		Token string `json:"token"`
	}
	if err := json.Unmarshal(body, &accepted); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Accepted", accepted.Token)

	body = poll(accepted.Token)
	png, err := base64.StdEncoding.DecodeString(string(body))
	if err != nil {
		log.Fatal(err)
	}
	if err := os.WriteFile("screenshot.png", png, 0o644); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Saved screenshot.png (%d bytes)\n", len(png))
}

Run it: go run main.go

Errors

Handle errors and retries

Errors are values: urlpipe() returns one for every refusal it will not retry, and main decides what to do with it. A 401 answers in plain text, so it is handled before the JSON decode; max is a builtin from Go 1.21.

main.go
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

var client = &http.Client{Timeout: 90 * time.Second}

// urlpipe POSTs a sync request and returns the result body. It retries the two
// 429s that clear by themselves and returns an error for everything else.
func urlpipe(path string, payload map[string]any) ([]byte, error) {
	payload["sync"] = true
	data, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}

	const attempts = 5
	for attempt := 0; attempt < attempts; attempt++ {
		req, err := http.NewRequest(http.MethodPost, "https://urlpipe.dev"+path, bytes.NewReader(data))
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Bearer "+os.Getenv("URLPIPE_API_KEY"))
		req.Header.Set("Content-Type", "application/json")

		res, err := client.Do(req)
		if err != nil {
			return nil, err
		}
		body, err := io.ReadAll(res.Body)
		res.Body.Close()
		if err != nil {
			return nil, err
		}

		switch res.StatusCode {
		case http.StatusOK:
			return body, nil
		case http.StatusUnauthorized:
			return nil, errors.New("401: the API key is missing or wrong, check URLPIPE_API_KEY")
		}

		var e struct {
			Code    string `json:"error"`
			Message string `json:"message"`
			Token   string `json:"token"`
		}
		_ = json.Unmarshal(body, &e) // a body that is not JSON leaves e empty
		detail := e.Code
		if e.Message != "" {
			detail = e.Code + ": " + e.Message
		}

		switch {
		case res.StatusCode == http.StatusTooManyRequests && e.Code == "rate_limited":
			// Sending too fast: Retry-After says how long the window has left.
			seconds, _ := strconv.Atoi(res.Header.Get("Retry-After"))
			time.Sleep(time.Duration(max(seconds, 1)) * time.Second)
		case res.StatusCode == http.StatusTooManyRequests && e.Code == "concurrency_limit":
			// Every parallel slot on your plan is busy with your own requests.
			time.Sleep(time.Duration(1<<attempt) * time.Second)
		case res.StatusCode == http.StatusGatewayTimeout:
			// Still running on our side; the token collects it from GET /result/:token.
			return nil, fmt.Errorf("504 processing_timeout: collect it later with token %s", e.Token)
		default:
			// 403 email_unverified, 422 (a bad parameter, or a page that would not load),
			// 429 quota_exceeded: sending the same request again gets the same answer.
			return nil, fmt.Errorf("%d: %s", res.StatusCode, detail)
		}
	}
	return nil, fmt.Errorf("429: still refused after %d attempts", attempts)
}

func main() {
	body, err := urlpipe("/screenshot", map[string]any{
		"url":          "https://example.com",
		"page_options": map[string]any{"block_cookie_banners": true},
	})
	if err != nil {
		log.Fatalf("URLpipe: %v", err)
	}

	png, err := base64.StdEncoding.DecodeString(string(body))
	if err != nil {
		log.Fatal(err)
	}
	if err := os.WriteFile("screenshot.png", png, 0o644); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Saved screenshot.png (%d bytes)\n", len(png))
}

Run it: go run main.go

Details

What to know about /screenshot

  • The default viewport is 1350 × 797 and the capture follows the page down to 16,384 px; a taller page is cut there.
  • Every response carries an X-Result-Url header: a link to the same image that needs no API key and stays valid for 30 days. Often you can store that link instead of the file.
  • PNG is the default; "format": "jpeg" or "webp" in screenshot_options makes a long page far smaller.
  • It captures images, not PDFs, and it does not record video.
  • A screenshot of the same URL with the same options is served from the cache for 7 days by default, free. Set max_age to refresh sooner.

Other languages

Take a screenshot of a website in another language

More Go: every Go recipe

FAQ

Frequently asked questions

Why is the screenshot response Base64 and not an image?
So the same body works in JSON, in a webhook payload and in an <img> data URI. Decode it with base64.StdEncoding.DecodeString, or skip decoding and use the X-Result-Url header, a direct link to the image.
How do I take a mobile screenshot?
Set screenshot_options.viewport_width to a phone width such as 390 and device_scale_factor to 2 or 3. The viewport can be anything from 320 to 1920 pixels wide.
Can I screenshot one element instead of the whole page?
Yes: screenshot_options takes a CSS selector and captures just that element. A selector that matches nothing is a 422, and costs nothing.
Do I need an SDK to call URLpipe from Go?
No module to fetch: net/http and encoding/json are standard library, and the API is one POST per job.

Get a key and run it.

Free plan, no card. Paste your key into URLPIPE_API_KEY and every program on this page runs as it is.