screenshotscout

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 16 Imported by: 0

README

Screenshot Scout Go SDK

The official Go SDK for the Screenshot Scout screenshot API.

Requirements

  • Go 1.25 or newer

Installation

go get github.com/screenshotscout/screenshotscout-go

Get your API credentials

Before using the SDK, sign up for Screenshot Scout or sign in to your account. Open the API Keys page, then copy your access key and secret key.

The access key is required by NewClient. The optional secret key enables signed requests. The SDK never reads either credential from environment variables on its own; applications pass credentials explicitly.

Capture a screenshot

Capture waits until Screenshot Scout returns the final screenshot response.

package main

import (
	"context"
	"log"
	"os"

	screenshotscout "github.com/screenshotscout/screenshotscout-go"
)

func main() {
	accessKey := os.Getenv("SCREENSHOTSCOUT_ACCESS_KEY")
	if accessKey == "" {
		log.Fatal("set SCREENSHOTSCOUT_ACCESS_KEY first")
	}

	client, err := screenshotscout.NewClient(accessKey, nil)
	if err != nil {
		log.Fatal(err)
	}
	fullPage := true
	response, err := client.Capture(
		context.Background(),
		"https://example.com",
		&screenshotscout.CaptureOptions{FullPage: &fullPage},
	)
	if err != nil {
		log.Fatal(err)
	}
	if response.Binary == nil {
		log.Fatal("Screenshot Scout returned a non-binary response")
	}
	if err := os.WriteFile("screenshot.png", response.Binary.Bytes, 0o600); err != nil {
		log.Fatal(err)
	}
}

Capture uses POST by default. An omitted ResponseType, or an explicit CaptureResponseTypeBinary, expects a binary response.

Request a JSON result

responseType := screenshotscout.CaptureResponseTypeJSON
response, err := client.Capture(
	context.Background(),
	"https://example.com",
	&screenshotscout.CaptureOptions{
		ResponseType: &responseType,
	},
)
if err != nil {
	log.Fatal(err)
}
if response.JSON == nil {
	log.Fatal("Screenshot Scout returned a non-JSON response")
}
result := response.JSON.Result
if result.ScreenshotURL != nil {
	fmt.Println(*result.ScreenshotURL)
}

CaptureResponse.Kind is either CaptureResponseKindBinary or CaptureResponseKindJSON, and exactly one of CaptureResponse.Binary and CaptureResponse.JSON is non-nil.

Use GET

POST is the default. Pass CaptureHTTPMethodGET as the final argument to use GET for a call:

format := screenshotscout.CaptureFormatWEBP
response, err := client.Capture(
	context.Background(),
	"https://example.com",
	&screenshotscout.CaptureOptions{Format: &format},
	screenshotscout.CaptureHTTPMethodGET,
)

The method selector is separate from CaptureOptions. Supplying any value other than CaptureHTTPMethodGET or CaptureHTTPMethodPOST returns a SerializationError.

Build a capture URL

BuildCaptureURL creates a URL without making an HTTP request. Use it when another application or an HTML <img> element needs to load the screenshot directly:

fullPage := true
blockAds := true
captureURL, err := client.BuildCaptureURL(
	"https://example.com",
	&screenshotscout.CaptureOptions{
		FullPage: &fullPage,
		BlockAds: &blockAds,
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(captureURL)

The generated URL contains the access key. A configured secret key signs it automatically; without a secret key, the URL is unsigned. Treat generated URLs as sensitive. Before exposing one to browsers or users, configure a secret key and enable Require signed requests on the API Keys page.

Signed requests

Pass the API key's secret key through ClientOptions. The secret is used locally and is never transmitted:

client, err := screenshotscout.NewClient(
	"YOUR_ACCESS_KEY",
	&screenshotscout.ClientOptions{SecretKey: "YOUR_SECRET_KEY"},
)

When a secret key is configured, the client signs capture requests and generated capture URLs automatically. See the signed requests guide.

Capture options

The target URL is the required second argument to Capture and the first argument to BuildCaptureURL. CaptureOptions provides the supported screenshot options:

  • Output: Format, ResponseType
  • Network and location: Country, Proxy, GeolocationLatitude, GeolocationLongitude, GeolocationAccuracy
  • Cookies and webpage headers: Cookies, Headers
  • Timing: Timeout, WaitUntil, NavigationTimeout, Delay
  • Device emulation: Device, DeviceViewportWidth, DeviceViewportHeight, DeviceScaleFactor, DeviceIsMobile, DeviceHasTouch, DeviceUserAgent
  • Page behavior: Timezone, MediaType, ColorScheme, ReducedMotion
  • Full page: FullPage, FullPagePreScroll, FullPagePreScrollStep, FullPagePreScrollStepDelay, FullPageMaxHeight
  • Blocking: BlockCookieBanners, BlockAds, BlockChatWidgets
  • DOM changes: HideSelectors, ClickSelectors, ClickAllSelectors, InjectCSS, InjectJS, BypassCSP
  • Framing: Selector, ClipX, ClipY, ClipWidth, ClipHeight
  • Image output: ImageWidth, ImageHeight, ImageMode, ImageAnchor, ImageAllowUpscale, ImageBackground, ImageQuality
  • PDF: PDFPaperFormat, PDFLandscape, PDFPrintBackground, PDFMargin, PDFMarginTop, PDFMarginRight, PDFMarginBottom, PDFMarginLeft, PDFScale
  • Caching: Cache, CacheTTL, CacheKey
  • Storage: StorageMode, StorageEndpoint, StorageBucket, StorageRegion, StorageObjectKey

Scalar fields are pointers. nil omits an option, while pointers to "", false, or zero transmit those values exactly. Empty repeated slices are omitted; non-empty slices preserve caller order and duplicates.

Documented string values are available as constants. You can also pass a value that does not have a constant by using an explicit conversion:

documented := screenshotscout.CaptureFormatWEBP
future := screenshotscout.CaptureFormat("future-format")

Screenshot Scout validates target URLs and option values. Invalid or incompatible values are returned as API errors. See the screenshot option reference.

Timeouts and cancellation

Use goroutines for concurrent captures. For timing and cancellation, two independent controls are available:

  • CaptureOptions.Timeout is the Screenshot Scout service-side capture budget in seconds.
  • The required context.Context controls each call and is the preferred place for call-specific deadlines or cancellation.
serviceTimeout := 180
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()

response, err := client.Capture(
	ctx,
	"https://example.com",
	&screenshotscout.CaptureOptions{Timeout: &serviceTimeout},
)

These controls are independent. Cancellation returns context.Canceled or context.DeadlineExceeded, which can be checked with errors.Is.

Client configuration and custom HTTP transport

ClientOptions supports:

  • SecretKey: optional signing secret
  • HTTPClient: optional reusable *http.Client

SDK requests do not follow redirects. An injected client's transport, cookie jar, and timeout remain in use, and the caller-owned client is not modified.

httpClient := &http.Client{Timeout: 5 * time.Minute}
client, err := screenshotscout.NewClient(
	"YOUR_ACCESS_KEY",
	&screenshotscout.ClientOptions{HTTPClient: httpClient},
)

Capture does not retry failed requests automatically or fetch a returned screenshot URL.

Raw responses and errors

Every successful CaptureResponse includes RawResponse, with the HTTP status, headers, content type, and body bytes. APIError and ResponseDecodingError provide the same response details.

Five error categories are available as concrete types and errors.Is sentinels:

  • ConfigurationError / ErrConfiguration
  • SerializationError / ErrSerialization
  • TransportError / ErrTransport
  • APIError / ErrAPI
  • ResponseDecodingError / ErrResponseDecoding
response, err := client.Capture(context.Background(), "https://example.com", nil)
if err != nil {
	var apiError *screenshotscout.APIError
	var transportError *screenshotscout.TransportError
	switch {
	case errors.As(err, &apiError):
		fmt.Println(apiError.StatusCode)
		if apiError.ErrorCode != nil {
			fmt.Println(*apiError.ErrorCode)
		}
		if apiError.ErrorMessage != nil {
			fmt.Println(*apiError.ErrorMessage)
		}
		fmt.Println(apiError.Errors, apiError.ResponseBody)
		fmt.Println(apiError.RawResponse.Headers)
	case errors.As(err, &transportError):
		fmt.Println(errors.Unwrap(transportError))
	case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
		fmt.Println("capture canceled:", err)
	default:
		fmt.Println(err)
	}
}

TransportError unwraps the native HTTP cause. APIError.ResponseBody retains the complete decoded JSON value when the failure body is valid JSON, including unrecognized fields.

License

MIT License. See LICENSE.

Documentation

Overview

Package screenshotscout provides a small, synchronous Go client for the inline Screenshot Scout capture API.

Client.Capture waits for the final buffered response. A required context controls cancellation, and callers can use ordinary goroutines for concurrent I/O. Client.BuildCaptureURL constructs a sensitive capture URL without performing network I/O.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrConfiguration identifies invalid client configuration.
	ErrConfiguration = errors.New("screenshotscout: configuration error")
	// ErrSerialization identifies values that cannot be serialized safely.
	ErrSerialization = errors.New("screenshotscout: serialization error")
	// ErrTransport identifies failures before a complete HTTP response body is received.
	ErrTransport = errors.New("screenshotscout: transport error")
	// ErrAPI identifies non-2xx Screenshot Scout HTTP responses.
	ErrAPI = errors.New("screenshotscout: API error")
	// ErrResponseDecoding identifies invalid or representation-mismatched 2xx responses.
	ErrResponseDecoding = errors.New("screenshotscout: response decoding error")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode   int
	ErrorCode    *string
	ErrorMessage *string
	Errors       []any
	ResponseBody any
	RawResponse  RawResponse
}

APIError reports a non-2xx Screenshot Scout response while retaining the parsed service fields, complete parsed body when available, and raw response.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

type BinaryCaptureResponse

type BinaryCaptureResponse struct {
	Bytes                  []byte
	ScreenshotURL          *string
	ScreenshotURLExpiresAt *string
	CacheStatus            *string
}

BinaryCaptureResponse contains a buffered binary capture result.

type CaptureColorScheme

type CaptureColorScheme string

CaptureColorScheme is an open string type for emulated color schemes.

const (
	CaptureColorSchemeAuto  CaptureColorScheme = "auto"
	CaptureColorSchemeDark  CaptureColorScheme = "dark"
	CaptureColorSchemeLight CaptureColorScheme = "light"
)

type CaptureFormat

type CaptureFormat string

CaptureFormat is an open string type for Screenshot Scout output formats.

const (
	CaptureFormatGIF  CaptureFormat = "gif"
	CaptureFormatJPEG CaptureFormat = "jpeg"
	CaptureFormatJPG  CaptureFormat = "jpg"
	CaptureFormatPDF  CaptureFormat = "pdf"
	CaptureFormatPNG  CaptureFormat = "png"
	CaptureFormatTIFF CaptureFormat = "tiff"
	CaptureFormatWEBP CaptureFormat = "webp"
)

type CaptureHTTPMethod

type CaptureHTTPMethod string

CaptureHTTPMethod is the closed, SDK-owned HTTP method selector for Capture.

const (
	CaptureHTTPMethodGET  CaptureHTTPMethod = "GET"
	CaptureHTTPMethodPOST CaptureHTTPMethod = "POST"
)

type CaptureImageAnchor

type CaptureImageAnchor string

CaptureImageAnchor is an open string type for image resize anchors.

const (
	CaptureImageAnchorBottom      CaptureImageAnchor = "bottom"
	CaptureImageAnchorBottomLeft  CaptureImageAnchor = "bottom_left"
	CaptureImageAnchorBottomRight CaptureImageAnchor = "bottom_right"
	CaptureImageAnchorCenter      CaptureImageAnchor = "center"
	CaptureImageAnchorLeft        CaptureImageAnchor = "left"
	CaptureImageAnchorRight       CaptureImageAnchor = "right"
	CaptureImageAnchorTop         CaptureImageAnchor = "top"
	CaptureImageAnchorTopLeft     CaptureImageAnchor = "top_left"
	CaptureImageAnchorTopRight    CaptureImageAnchor = "top_right"
)

type CaptureImageMode

type CaptureImageMode string

CaptureImageMode is an open string type for image resize modes.

const (
	CaptureImageModeFill    CaptureImageMode = "fill"
	CaptureImageModeFit     CaptureImageMode = "fit"
	CaptureImageModeStretch CaptureImageMode = "stretch"
)

type CaptureMediaType

type CaptureMediaType string

CaptureMediaType is an open string type for emulated CSS media types.

const (
	CaptureMediaTypePrint  CaptureMediaType = "print"
	CaptureMediaTypeScreen CaptureMediaType = "screen"
)

type CaptureOptions

type CaptureOptions struct {
	// Target and output.
	Format       *CaptureFormat
	ResponseType *CaptureResponseType

	// Network and location.
	Country              *string
	Proxy                *string
	GeolocationLatitude  *float64
	GeolocationLongitude *float64
	GeolocationAccuracy  *float64

	// Cookies and webpage request headers. Order and duplicates are preserved.
	Cookies []string
	Headers []string

	// Navigation and service-side timing.
	Timeout           *int
	WaitUntil         *CaptureWaitUntil
	NavigationTimeout *int
	Delay             *int

	// Viewport and device emulation.
	Device               *string
	DeviceViewportWidth  *int
	DeviceViewportHeight *int
	DeviceScaleFactor    *float64
	DeviceIsMobile       *bool
	DeviceHasTouch       *bool
	DeviceUserAgent      *string

	// Page behavior and preferences.
	Timezone      *string
	MediaType     *CaptureMediaType
	ColorScheme   *CaptureColorScheme
	ReducedMotion *bool

	// Full-page capture and pre-scroll behavior.
	FullPage                   *bool
	FullPagePreScroll          *bool
	FullPagePreScrollStep      *int
	FullPagePreScrollStepDelay *int
	FullPageMaxHeight          *int

	// Blocking.
	BlockCookieBanners *bool
	BlockAds           *bool
	BlockChatWidgets   *bool

	// DOM interactions and injections. Order and duplicates are preserved.
	HideSelectors     []string
	ClickSelectors    []string
	ClickAllSelectors []string
	InjectCSS         []string
	InjectJS          []string
	BypassCSP         *bool

	// Framing and selection.
	Selector   *string
	ClipX      *int
	ClipY      *int
	ClipWidth  *int
	ClipHeight *int

	// Image resizing and quality.
	ImageWidth        *int
	ImageHeight       *int
	ImageMode         *CaptureImageMode
	ImageAnchor       *CaptureImageAnchor
	ImageAllowUpscale *bool
	ImageBackground   *string
	ImageQuality      *int

	// PDF.
	PDFPaperFormat     *CapturePDFPaperFormat
	PDFLandscape       *bool
	PDFPrintBackground *bool
	PDFMargin          *string
	PDFMarginTop       *string
	PDFMarginRight     *string
	PDFMarginBottom    *string
	PDFMarginLeft      *string
	PDFScale           *float64

	// Caching.
	Cache    *bool
	CacheTTL *int
	CacheKey *string

	// Storage.
	StorageMode      *CaptureStorageMode
	StorageEndpoint  *string
	StorageBucket    *string
	StorageRegion    *string
	StorageObjectKey *string
}

CaptureOptions contains Screenshot Scout service options. URL, access_key, signature, and the request HTTP method are deliberately separate.

Pointer fields preserve the distinction between omission and explicit zero, false, or an empty string. Empty repeated slices are omitted.

type CapturePDFPaperFormat

type CapturePDFPaperFormat string

CapturePDFPaperFormat is an open string type for PDF paper formats.

const (
	CapturePDFPaperFormatA3      CapturePDFPaperFormat = "a3"
	CapturePDFPaperFormatA4      CapturePDFPaperFormat = "a4"
	CapturePDFPaperFormatContent CapturePDFPaperFormat = "content"
	CapturePDFPaperFormatLegal   CapturePDFPaperFormat = "legal"
	CapturePDFPaperFormatLetter  CapturePDFPaperFormat = "letter"
	CapturePDFPaperFormatTabloid CapturePDFPaperFormat = "tabloid"
)

type CaptureResponse

type CaptureResponse struct {
	Kind        CaptureResponseKind
	Binary      *BinaryCaptureResponse
	JSON        *JSONCaptureResponse
	RawResponse RawResponse
}

CaptureResponse is the discriminated Go response shape. Exactly one of Binary and JSON is non-nil on a successful return.

type CaptureResponseKind

type CaptureResponseKind string

CaptureResponseKind identifies which CaptureResponse member is populated.

const (
	CaptureResponseKindBinary CaptureResponseKind = "binary"
	CaptureResponseKindJSON   CaptureResponseKind = "json"
)

type CaptureResponseType

type CaptureResponseType string

CaptureResponseType is an open string type for successful response representations.

const (
	CaptureResponseTypeBinary CaptureResponseType = "binary"
	CaptureResponseTypeJSON   CaptureResponseType = "json"
)

type CaptureResult

type CaptureResult struct {
	ScreenshotURL          *string
	ScreenshotURLExpiresAt *string
	CacheStatus            *string
	AdditionalFields       map[string]any
}

CaptureResult contains documented JSON result metadata and any additional response fields returned by the service.

type CaptureStorageMode

type CaptureStorageMode string

CaptureStorageMode is an open string type for screenshot storage modes.

const (
	CaptureStorageModeExternal CaptureStorageMode = "external"
	CaptureStorageModeManaged  CaptureStorageMode = "managed"
)

type CaptureWaitUntil

type CaptureWaitUntil string

CaptureWaitUntil is an open string type for navigation completion conditions.

const (
	CaptureWaitUntilDOMContentLoaded CaptureWaitUntil = "domcontentloaded"
	CaptureWaitUntilLoad             CaptureWaitUntil = "load"
	CaptureWaitUntilNetworkIdle0     CaptureWaitUntil = "networkidle0"
	CaptureWaitUntilNetworkIdle2     CaptureWaitUntil = "networkidle2"
)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a reusable Screenshot Scout API client.

func NewClient

func NewClient(accessKey string, options *ClientOptions) (*Client, error)

NewClient creates a reusable client. The access key is configured once and is sent in the Authorization header for Capture calls.

func (*Client) BuildCaptureURL

func (client *Client) BuildCaptureURL(targetURL string, options *CaptureOptions) (string, error)

BuildCaptureURL constructs a sensitive GET capture URL without making an HTTP request. The access key is included in the query, and a configured secret key signs the URL automatically.

Example
package main

import (
	"fmt"

	screenshotscout "github.com/screenshotscout/screenshotscout-go"
)

func main() {
	client, err := screenshotscout.NewClient("ak_test", nil)
	if err != nil {
		panic(err)
	}
	fullPage := true
	captureURL, err := client.BuildCaptureURL(
		"https://example.com",
		&screenshotscout.CaptureOptions{FullPage: &fullPage},
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(captureURL)
}
Output:
https://api.screenshotscout.com/v1/capture?access_key=ak_test&url=https%3A%2F%2Fexample.com&full_page=true

func (*Client) Capture

func (client *Client) Capture(
	ctx context.Context,
	targetURL string,
	options *CaptureOptions,
	method ...CaptureHTTPMethod,
) (*CaptureResponse, error)

Capture performs one inline Screenshot Scout request and waits for the final buffered response. POST is used when method is omitted. At most one method may be supplied, and it must be CaptureHTTPMethodGET or CaptureHTTPMethodPOST. Cancellation follows the supplied context's normal semantics.

type ClientOptions

type ClientOptions struct {
	SecretKey  string
	HTTPClient *http.Client
}

ClientOptions configures signing and HTTP transport for a reusable Client.

type ConfigurationError

type ConfigurationError struct {
	Message string
	Cause   error
}

ConfigurationError reports invalid client configuration.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

func (*ConfigurationError) Is

func (e *ConfigurationError) Is(target error) bool

func (*ConfigurationError) Unwrap

func (e *ConfigurationError) Unwrap() error

type JSONCaptureResponse

type JSONCaptureResponse struct {
	Result CaptureResult
}

JSONCaptureResponse contains a decoded JSON capture result.

type RawResponse

type RawResponse struct {
	StatusCode  int
	Status      string
	Headers     http.Header
	ContentType string
	Body        []byte
}

RawResponse contains the exact buffered HTTP response data retained on successes and API failures.

type ResponseDecodingError

type ResponseDecodingError struct {
	Message     string
	RawResponse RawResponse
	Cause       error
}

ResponseDecodingError reports an invalid or representation-mismatched 2xx response while retaining the raw response.

func (*ResponseDecodingError) Error

func (e *ResponseDecodingError) Error() string

func (*ResponseDecodingError) Is

func (e *ResponseDecodingError) Is(target error) bool

func (*ResponseDecodingError) Unwrap

func (e *ResponseDecodingError) Unwrap() error

type SerializationError

type SerializationError struct {
	Message string
	Option  string
	Cause   error
}

SerializationError reports a value that cannot be represented safely on the wire.

func (*SerializationError) Error

func (e *SerializationError) Error() string

func (*SerializationError) Is

func (e *SerializationError) Is(target error) bool

func (*SerializationError) Unwrap

func (e *SerializationError) Unwrap() error

type TransportError

type TransportError struct {
	Message string
	Cause   error
}

TransportError reports a failure before a complete HTTP response body is available. Unwrap exposes the native transport cause.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Is

func (e *TransportError) Is(target error) bool

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Directories

Path Synopsis
examples
binary command
capture-url command
json command

Jump to

Keyboard shortcuts

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