How to take a website screenshot in Go

By URLBooth · Published · Last updated

To take a website screenshot in Go, build an authenticated POST request with net/http to the URLBooth endpoint /v1/screenshots, send a JSON body with the page URL and an Authorization: Bearer key, then copy the response body, which is the image, into a file with io.Copy. No third-party modules are needed.

What is the minimal Go program with net/http?

This is a complete main.go using only the standard library. Export URLBOOTH_API_KEY and run go run main.go. The API needs the Pro plan; keys are created in the dashboard under API keys.

Go example
package main
​
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
​
type apiError struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"requestId"`
} `json:"error"`
}
​
func main() {
body, _ := json.Marshal(map[string]any{"url": "https://example.com"})
​
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
​
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://urlbooth.com/v1/screenshots", bytes.NewReader(body))
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("URLBOOTH_API_KEY"))
req.Header.Set("Content-Type", "application/json")
​
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
​
if resp.StatusCode != http.StatusOK {
var e apiError
_ = json.NewDecoder(resp.Body).Decode(&e)
panic(fmt.Sprintf("%d %s: %s", resp.StatusCode, e.Error.Code, e.Error.Message))
}
​
file, err := os.Create("screenshot.png")
if err != nil {
panic(err)
}
defer file.Close()
​
if _, err := io.Copy(file, resp.Body); err != nil {
panic(err)
}
fmt.Println("saved", resp.Header.Get("X-Screenshot-Id"))
}

The order of operations is deliberate. Check resp.StatusCode before you read the body as an image, because on failure the body is a small JSON error and you would otherwise write it into a .png. defer resp.Body.Close() goes right after the error check on Do, since Do returns a non-nil body whenever err is nil, whatever the status. And io.Copy streams from the response into the file in chunks, so the image is never held entirely in memory.

How do you set a timeout with context?

http.DefaultClient has no timeout, so a stalled connection would block forever. The idiomatic fix is a context deadline: context.WithTimeout for 60 seconds, passed to http.NewRequestWithContext. The server gives up after about 45 seconds and returns a 504 capture_timeout, so 60 leaves room for that response to arrive. A context deadline covers the whole exchange, including reading the body, which is what you want when streaming a large image. You can set Client.Timeout instead for a single global limit, but per-request contexts let a caller cancel a capture early, for example when a user closes a request.

How do you set the device, format, full page, cleanup and frame?

Use a struct with JSON tags rather than a map so the field names are checked in one place. The fields are url, device, format (png, jpeg or webp), fullPage, cleanup and frame. One Go-specific catch: cleanup defaults to true on the server, but a plain bool with omitempty drops false, so you could never turn it off. Make it a *bool so you can send an explicit false. Device ids such as macbook-air-13, iphone-17-pro and ipad-air-11 are in the API docs. Frames are disabled for full-page captures.

Struct payload
package main
​
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
​
// request mirrors the JSON body. Pointers and omitempty keep unset fields out.
type request struct {
URL string `json:"url"`
Device string `json:"device,omitempty"`
Format string `json:"format,omitempty"`
FullPage bool `json:"fullPage,omitempty"`
Cleanup *bool `json:"cleanup,omitempty"`
Frame bool `json:"frame,omitempty"`
}
​
func main() {
cleanup := true
payload, _ := json.Marshal(request{
URL: "https://example.com",
Device: "macbook-air-13",
Format: "jpeg",
Cleanup: &cleanup,
Frame: true,
})
​
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
​
req, _ := http.NewRequestWithContext(ctx, http.MethodPost,
"https://urlbooth.com/v1/screenshots", bytes.NewReader(payload))
req.Header.Set("Authorization", "Bearer "+os.Getenv("URLBOOTH_API_KEY"))
req.Header.Set("Content-Type", "application/json")
​
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic(fmt.Sprintf("capture failed: HTTP %d", resp.StatusCode))
}
​
file, _ := os.Create("pricing.jpg")
defer file.Close()
if _, err := io.Copy(file, resp.Body); err != nil {
panic(err)
}
}

How do you download a saved screenshot later?

Read resp.Header.Get("X-Screenshot-Id") after a successful capture. The stored copy lives for two days (the X-Expires-At header gives the time) and can be fetched with a GET to /v1/screenshots/{id}/image using the same key. This also lets you recover when your process died after the server had already captured the page.

Download a stored screenshot
package main
​
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"time"
)
​
func main() {
id := os.Args[1] // the X-Screenshot-Id value from an earlier capture
​
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
​
req, _ := http.NewRequestWithContext(ctx, http.MethodGet,
"https://urlbooth.com/v1/screenshots/"+url.PathEscape(id)+"/image", nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("URLBOOTH_API_KEY"))
​
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic(fmt.Sprintf("download failed: HTTP %d", resp.StatusCode))
}
​
file, _ := os.Create("again.png")
defer file.Close()
if _, err := io.Copy(file, resp.Body); err != nil {
panic(err)
}
}

How do you handle errors and rate limits in Go?

Go gives you two kinds of failure. A non-nil err from Do means no HTTP response arrived (network error, or your context expired). A response with a non-200 status is an API error with a JSON body of code, message and requestId. Pro allows 60 requests per minute, 10 concurrent captures and 10,000 per day. Retry 429 rate_limited after the Retry-After seconds, and 503 capture_unavailable and 504 capture_timeout with backoff. A daily_limit_reached 429 resets at 00:00 UTC, so a long wait is not worth it. Do not retry 400, 401 or 402. Cancel the per-attempt context once you finish reading each response.

Retry helper
package main
​
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
​
var client = &http.Client{} // deadlines come from the per-request context
​
func capture(ctx context.Context, payload []byte, attempts int) ([]byte, error) {
for attempt := 1; ; attempt++ {
reqCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost,
"https://urlbooth.com/v1/screenshots", bytes.NewReader(payload))
if err != nil {
cancel()
return nil, err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("URLBOOTH_API_KEY"))
req.Header.Set("Content-Type", "application/json")
​
resp, err := client.Do(req)
if err != nil {
cancel()
return nil, err
}
​
if resp.StatusCode == http.StatusOK {
image, err := io.ReadAll(resp.Body)
resp.Body.Close()
cancel()
return image, err
}
​
var e struct {
Error struct {
Code string `json:"code"`
RequestID string `json:"requestId"`
} `json:"error"`
}
_ = json.NewDecoder(resp.Body).Decode(&e)
resp.Body.Close()
cancel()
​
retryable := resp.StatusCode == 429 || resp.StatusCode == 503 || resp.StatusCode == 504
if !retryable || attempt == attempts {
return nil, fmt.Errorf("%d %s (request %s)", resp.StatusCode, e.Error.Code, e.Error.RequestID)
}
​
wait := time.Duration(1<<attempt) * time.Second
if s, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
wait = time.Duration(s) * time.Second
}
select {
case <-time.After(wait):
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
​
func main() {
payload, _ := json.Marshal(map[string]any{"url": "https://example.com"})
image, err := capture(context.Background(), payload, 3)
if err != nil {
panic(err)
}
if err := os.WriteFile("screenshot.png", image, 0o644); err != nil {
panic(err)
}
}

How do you capture many URLs with goroutines?

Goroutines make it easy to exceed the limits by accident. A buffered channel used as a semaphore caps in-flight captures at ten, matching the concurrent limit. The 60 per minute limit still applies, so large batches rely on the retry helper honoring Retry-After. Reuse one http.Client so connections are pooled.

Bounded concurrency
// Reuses capture() from the retry helper above.
package main
​
import (
"context"
"encoding/json"
"fmt"
"os"
"sync"
)
​
func captureAll(urls []string) {
sem := make(chan struct{}, 10) // 10 concurrent captures on Pro
var wg sync.WaitGroup
​
for i, u := range urls {
wg.Add(1)
sem <- struct{}{}
go func(i int, u string) {
defer wg.Done()
defer func() { <-sem }()
​
payload, _ := json.Marshal(map[string]any{"url": u})
image, err := capture(context.Background(), payload, 3)
if err != nil {
fmt.Println(u, err)
return
}
_ = os.WriteFile(fmt.Sprintf("shot-%d.png", i), image, 0o644)
}(i, u)
}
wg.Wait()
}

When should you run a headless browser yourself instead?

Go has solid browser automation libraries such as chromedp. Use one if you must log in, script interactions or capture internal pages; you then manage Chromium, fonts and memory in your own containers. For public URLs, a single HTTP call is less to operate. See screenshot API vs running Puppeteer yourself for the comparison.

Where to go next