e2b

package module
v0.0.0-...-55b56c6 Latest Latest
Warning

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

Go to latest
Published: May 30, 2026 License: MIT Imports: 13 Imported by: 0

README

go-e2b

CI Lint Security Go Reference Go Version

A Go SDK for the E2B cloud sandbox API. E2B provides lightweight microVMs you can use to safely run arbitrary code in ephemeral environments.

Installation

go get github.com/matiasinsaurralde/go-e2b

Requirements

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    e2b "github.com/matiasinsaurralde/go-e2b"
)

func main() {
    client, err := e2b.NewClient(e2b.ClientConfig{
        APIKey: os.Getenv("E2B_API_KEY"),
    })
    if err != nil {
        log.Fatal(err)
    }

    sandbox, err := client.NewSandbox(context.Background(), e2b.SandboxConfig{
        Template: "base",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer sandbox.Close()

    result, err := sandbox.Commands.Run("echo", []string{"hello, world"})
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result.Stdout)     // hello, world
    fmt.Println(result.ExitCode)   // 0
}

See examples/ for more usage patterns.

Usage

Creating a Client and Sandbox
client, err := e2b.NewClient(e2b.ClientConfig{
    APIKey:        "your-api-key",       // or set E2B_API_KEY env var
    APIBaseURL:    "https://api.e2b.app", // optional
    SandboxDomain: "e2b.app",             // optional
})
if err != nil {
    log.Fatal(err)
}

sandbox, err := client.NewSandbox(context.Background(), e2b.SandboxConfig{
    Template: "base",               // sandbox template (default: "base")
    Timeout:  300,                  // lifetime in seconds (default: 300)
    EnvVars:  map[string]string{    // environment variables
        "MY_VAR": "value",
    },
})

The base template includes Python 3.11, Node.js 20, npm, Yarn, git, and the GitHub CLI.

Running Commands
// Simple command
result, err := sandbox.Commands.Run("python3", []string{"-c", "print('hello')"})

// With options
result, err := sandbox.Commands.Run(
    "bash", []string{"-c", "echo $FOO"},
    e2b.WithEnv(map[string]string{"FOO": "bar"}),
    e2b.WithCwd("/tmp"),
    e2b.WithUser("ubuntu"),
    e2b.WithTimeout(30 * time.Second),
)

fmt.Println(result.Stdout)
fmt.Println(result.Stderr)
fmt.Println(result.ExitCode)
Context Support
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

client, err := e2b.NewClient(e2b.ClientConfig{APIKey: apiKey})
if err != nil {
    log.Fatal(err)
}

sandbox, err := client.NewSandbox(ctx, e2b.SandboxConfig{Template: "base"})
if err != nil {
    log.Fatal(err)
}
defer sandbox.Close()

result, err := sandbox.Commands.RunWithContext(ctx, "sleep", []string{"5"})
Command Options
Option Description
WithEnv(map[string]string) Set environment variables for the command
WithCwd(string) Set the working directory
WithUser(string) Set the user to run the command as
WithTimeout(time.Duration) Set a per-command execution timeout

Configuration

Configuration can be provided via ClientConfig / SandboxConfig fields or environment variables:

Field Env Var Default Description
ClientConfig.APIKey E2B_API_KEY E2B API key (required)
ClientConfig.APIBaseURL E2B_API_URL https://api.e2b.app API base URL
ClientConfig.SandboxDomain E2B_SANDBOX_URL e2b.app Sandbox domain
SandboxConfig.Template base Sandbox template ID
SandboxConfig.Timeout 300 Sandbox lifetime in seconds

Error Handling

import e2b "github.com/matiasinsaurralde/go-e2b"

_, err := e2b.NewClient(e2b.ClientConfig{APIKey: apiKey})
switch {
case errors.As(err, &e2b.SandboxNotFoundError{}):
    // sandbox not found
case errors.As(err, &e2b.TimeoutError{}):
    // operation timed out
case errors.As(err, &e2b.Error{}):
    // generic E2B error
}

Development

Regenerating Proto Bindings

The Connect RPC client is generated from e2b-dev/infra proto definitions using buf.

# Install tools
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install connectrpc.com/connect/cmd/protoc-gen-connect-go@latest

# Regenerate
make generate

# Sync proto from upstream
make proto-sync

# Upgrade to latest upstream commit
make proto-upgrade

See DEVELOPMENT.md for details.

License

MIT

Documentation

Overview

Package e2b provides a Go client for the E2B cloud sandbox API.

E2B sandboxes are lightweight microVMs that can run commands, access a filesystem, and be configured with environment variables.

Basic usage:

client, err := e2b.NewClient(e2b.ClientConfig{
    APIKey: os.Getenv("E2B_API_KEY"),
})
if err != nil {
    log.Fatal(err)
}

sandbox, err := client.NewSandbox(context.Background(), e2b.SandboxConfig{
    Template: "base",
    EnvVars:  map[string]string{"VALUE": "hello"},
})
if err != nil {
    log.Fatal(err)
}
defer sandbox.Close()

result, err := sandbox.Commands.Run("echo", []string{"hello"})
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.Stdout)

Index

Constants

View Source
const (
	// DefaultAPIBaseURL is the default E2B API endpoint.
	DefaultAPIBaseURL = "https://api.e2b.app"

	// DefaultTemplate is the default sandbox template.
	DefaultTemplate = "base"

	// DefaultTimeout is the default sandbox lifetime in seconds.
	DefaultTimeout = 300

	// DefaultCommandTimeout is the default command execution timeout.
	DefaultCommandTimeout = 60 * time.Second
)

Variables

This section is empty.

Functions

func WithFileUser

func WithFileUser(user string) fileUserOption

WithFileUser sets the sandbox user for the file operation. The returned value satisfies both ReadOption and WriteOption.

Types

type Client

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

Client is the E2B API client. Create one with NewClient and reuse it for all operations — it holds shared configuration like the API key.

func NewClient

func NewClient(cfgs ...ClientConfig) (*Client, error)

NewClient creates a new E2B client. If no config is provided, the API key is read from the E2B_API_KEY environment variable.

func (*Client) ListSandboxes

func (c *Client) ListSandboxes(ctx context.Context) ([]SandboxInfo, error)

ListSandboxes returns all running sandboxes for this client's API key.

func (*Client) ListSnapshots

func (c *Client) ListSnapshots(ctx context.Context, opts ...ListSnapshotsOption) (*ListSnapshotsResult, error)

ListSnapshots returns snapshots for this client's API key.

func (*Client) NewSandbox

func (c *Client) NewSandbox(ctx context.Context, cfgs ...SandboxConfig) (*Sandbox, error)

NewSandbox creates a new E2B sandbox microVM. The caller should call Close when the sandbox is no longer needed.

type ClientConfig

type ClientConfig struct {
	// APIKey is the E2B API key. If empty, the E2B_API_KEY environment variable is used.
	APIKey string

	// APIBaseURL overrides the default API base URL.
	APIBaseURL string

	// SandboxDomain overrides the default sandbox domain.
	SandboxDomain string

	// HTTPClient is the HTTP client used for API requests.
	// If nil, http.DefaultClient is used.
	HTTPClient *http.Client
}

ClientConfig configures a new Client.

type CommandResult

type CommandResult struct {
	// Stdout is the standard output of the command.
	Stdout string

	// Stderr is the standard error output of the command.
	Stderr string

	// ExitCode is the process exit code.
	ExitCode int
}

CommandResult holds the output of a completed command.

type CommandService

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

CommandService provides command execution within a sandbox.

func (*CommandService) Run

func (c *CommandService) Run(cmd string, args []string, opts ...RunOption) (*CommandResult, error)

Run executes a command in the sandbox and returns the result. It blocks until the command completes.

func (*CommandService) RunWithContext

func (c *CommandService) RunWithContext(ctx context.Context, cmd string, args []string, opts ...RunOption) (*CommandResult, error)

RunWithContext executes a command in the sandbox using the provided context for cancellation and deadline control.

type Error

type Error struct {
	// StatusCode is the HTTP status code, if applicable.
	StatusCode int

	// Message describes what went wrong.
	Message string
}

Error represents an error returned by the E2B API or SDK.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type FileInfo

type FileInfo struct {
	Name string `json:"name"`
	Path string `json:"path"`
	Type string `json:"type,omitempty"`
}

FileInfo describes a file written to the sandbox filesystem.

type FileNotFoundError

type FileNotFoundError struct {
	Path string
}

FileNotFoundError is returned when the requested path does not exist in the sandbox.

func (*FileNotFoundError) Error

func (e *FileNotFoundError) Error() string

Error implements the error interface.

type FilesystemService

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

FilesystemService provides file read and write operations within a sandbox.

func (*FilesystemService) Read

func (f *FilesystemService) Read(ctx context.Context, path string, opts ...ReadOption) (io.ReadCloser, error)

Read fetches the raw content of the file at path inside the sandbox. The caller must close the returned ReadCloser when done. For small files, ReadBytes or ReadString are more convenient.

func (*FilesystemService) ReadBytes

func (f *FilesystemService) ReadBytes(ctx context.Context, path string, opts ...ReadOption) ([]byte, error)

ReadBytes fetches the full content of the file at path as a byte slice.

func (*FilesystemService) ReadString

func (f *FilesystemService) ReadString(ctx context.Context, path string, opts ...ReadOption) (string, error)

ReadString fetches the full content of the file at path as a string.

func (*FilesystemService) Write

func (f *FilesystemService) Write(ctx context.Context, path string, r io.Reader, opts ...WriteOption) (*FileInfo, error)

Write uploads data from r to path inside the sandbox. The file is created if it does not exist and overwritten if it does. Parent directories are created automatically by envd. r may be any io.Reader: *os.File, *bytes.Reader, strings.NewReader, io.Pipe, etc.

func (*FilesystemService) WriteBytes

func (f *FilesystemService) WriteBytes(ctx context.Context, path string, b []byte, opts ...WriteOption) (*FileInfo, error)

WriteBytes writes b to path inside the sandbox.

func (*FilesystemService) WriteString

func (f *FilesystemService) WriteString(ctx context.Context, path string, s string, opts ...WriteOption) (*FileInfo, error)

WriteString writes s to path inside the sandbox.

type ListSnapshotsOption

type ListSnapshotsOption func(*listSnapshotsParams)

ListSnapshotsOption configures a ListSnapshots request.

func WithSnapshotLimit

func WithSnapshotLimit(n int) ListSnapshotsOption

WithSnapshotLimit sets the maximum number of snapshots to return (default 100).

func WithSnapshotNextToken

func WithSnapshotNextToken(token string) ListSnapshotsOption

WithSnapshotNextToken sets the pagination token from a previous ListSnapshotsResult.

func WithSnapshotSandboxID

func WithSnapshotSandboxID(id string) ListSnapshotsOption

WithSnapshotSandboxID filters snapshots by the source sandbox ID.

type ListSnapshotsResult

type ListSnapshotsResult struct {
	Snapshots []SnapshotInfo
	NextToken string
}

ListSnapshotsResult holds the result of a ListSnapshots call, including pagination.

type LogsOption

type LogsOption func(*logsParams)

LogsOption configures a Logs request.

func WithDirection

func WithDirection(d string) LogsOption

WithDirection sets the sort order: "forward" (oldest first) or "backward" (newest first, default).

func WithLevel

func WithLevel(l string) LogsOption

WithLevel filters logs by level: "debug", "info", "warn", or "error".

func WithLimit

func WithLimit(n int) LogsOption

WithLimit sets the maximum number of log entries to return (default 1000).

func WithSearch

func WithSearch(q string) LogsOption

WithSearch filters logs by a text search on the message field.

type ReadOption

type ReadOption interface {
	// contains filtered or unexported methods
}

ReadOption configures a Read, ReadBytes, or ReadString call.

func WithReadTimeout

func WithReadTimeout(d time.Duration) ReadOption

WithReadTimeout overrides the HTTP timeout for a Read call.

type RunOption

type RunOption func(*runConfig)

RunOption configures a single command execution.

func WithCwd

func WithCwd(cwd string) RunOption

WithCwd sets the working directory for the command.

func WithEnv

func WithEnv(envs map[string]string) RunOption

WithEnv sets environment variables for the command.

func WithTimeout

func WithTimeout(d time.Duration) RunOption

WithTimeout sets the command timeout. Defaults to DefaultCommandTimeout (60s).

func WithUser

func WithUser(user string) RunOption

WithUser sets the user to run the command as.

type Sandbox

type Sandbox struct {
	// ID is the unique identifier of the sandbox.
	ID string

	// Commands provides command execution within the sandbox.
	Commands *CommandService

	// Filesystem provides file read and write operations within the sandbox.
	Filesystem *FilesystemService
	// contains filtered or unexported fields
}

Sandbox represents a running E2B sandbox microVM.

func (*Sandbox) Close

func (s *Sandbox) Close() error

Close destroys the sandbox, freeing all associated resources.

func (*Sandbox) CloseWithContext

func (s *Sandbox) CloseWithContext(ctx context.Context) error

CloseWithContext destroys the sandbox using the provided context.

func (*Sandbox) CreateSnapshot

func (s *Sandbox) CreateSnapshot(ctx context.Context, name ...string) (*SnapshotInfo, error)

CreateSnapshot creates a snapshot of the sandbox's current state. An optional name can be provided; if omitted, the API generates an ID.

func (*Sandbox) Info

func (s *Sandbox) Info() (*SandboxInfo, error)

Info retrieves detailed information about the sandbox.

func (*Sandbox) InfoWithContext

func (s *Sandbox) InfoWithContext(ctx context.Context) (*SandboxInfo, error)

InfoWithContext retrieves detailed information about the sandbox using the provided context.

func (*Sandbox) Logs

func (s *Sandbox) Logs(opts ...LogsOption) ([]SandboxLogEntry, error)

Logs retrieves structured log entries for the sandbox.

func (*Sandbox) LogsWithContext

func (s *Sandbox) LogsWithContext(ctx context.Context, opts ...LogsOption) ([]SandboxLogEntry, error)

LogsWithContext retrieves structured log entries using the provided context.

func (*Sandbox) Metrics

func (s *Sandbox) Metrics() ([]SandboxMetric, error)

Metrics retrieves resource usage metrics for the sandbox.

func (*Sandbox) MetricsWithContext

func (s *Sandbox) MetricsWithContext(ctx context.Context) ([]SandboxMetric, error)

MetricsWithContext retrieves resource usage metrics using the provided context.

func (*Sandbox) Pause

func (s *Sandbox) Pause() error

Pause pauses the sandbox, stopping billing while preserving state. A paused sandbox can be resumed with Resume.

func (*Sandbox) PauseWithContext

func (s *Sandbox) PauseWithContext(ctx context.Context) error

PauseWithContext pauses the sandbox using the provided context.

func (*Sandbox) Resume

func (s *Sandbox) Resume(timeoutSeconds int) error

Resume resumes a paused sandbox with the given lifetime timeout in seconds.

func (*Sandbox) ResumeWithContext

func (s *Sandbox) ResumeWithContext(ctx context.Context, timeoutSeconds int) error

ResumeWithContext resumes a paused sandbox using the provided context.

func (*Sandbox) SetTimeout

func (s *Sandbox) SetTimeout(timeoutSeconds int) error

SetTimeout updates the sandbox lifetime timeout in seconds.

func (*Sandbox) SetTimeoutWithContext

func (s *Sandbox) SetTimeoutWithContext(ctx context.Context, timeoutSeconds int) error

SetTimeoutWithContext updates the sandbox lifetime timeout using the provided context.

type SandboxConfig

type SandboxConfig struct {
	// Template is the sandbox template ID. Defaults to "base".
	Template string

	// Timeout is the sandbox lifetime in seconds. Defaults to 300.
	Timeout int

	// EnvVars are environment variables set in the sandbox.
	EnvVars map[string]string
}

SandboxConfig holds the configuration for creating a new sandbox.

type SandboxInfo

type SandboxInfo struct {
	ID           string           `json:"sandboxID"`
	Alias        string           `json:"alias,omitempty"`
	ClientID     string           `json:"clientID,omitempty"`
	Template     string           `json:"templateID"`
	State        string           `json:"state"`
	CPUCount     int              `json:"cpuCount"`
	MemoryMB     int              `json:"memoryMB"`
	DiskSizeMB   int              `json:"diskSizeMB"`
	StartedAt    string           `json:"startedAt"`
	EndAt        string           `json:"endAt,omitempty"`
	EnvdVersion  string           `json:"envdVersion,omitempty"`
	Lifecycle    SandboxLifecycle `json:"lifecycle,omitempty"`
	VolumeMounts []VolumeMount    `json:"volumeMounts,omitempty"`
}

SandboxInfo holds details about a sandbox.

type SandboxLifecycle

type SandboxLifecycle struct {
	AutoResume bool   `json:"autoResume"`
	OnTimeout  string `json:"onTimeout"` // "keep" or "kill"
}

SandboxLifecycle holds lifecycle configuration for a sandbox.

type SandboxLogEntry

type SandboxLogEntry struct {
	Level     string            `json:"level"`
	Message   string            `json:"message"`
	Timestamp string            `json:"timestamp"`
	Fields    map[string]string `json:"fields"`
}

SandboxLogEntry holds a single structured log entry from a sandbox.

type SandboxMetric

type SandboxMetric struct {
	CPUCount      int     `json:"cpuCount"`
	CPUUsedPct    float64 `json:"cpuUsedPct"`
	MemTotal      int64   `json:"memTotal"`
	MemUsed       int64   `json:"memUsed"`
	MemCache      int64   `json:"memCache"`
	DiskTotal     int64   `json:"diskTotal"`
	DiskUsed      int64   `json:"diskUsed"`
	Timestamp     string  `json:"timestamp"`
	TimestampUnix int64   `json:"timestampUnix"`
}

SandboxMetric holds a single resource usage snapshot for a sandbox.

type SandboxNotFoundError

type SandboxNotFoundError struct {
	SandboxID string
}

SandboxNotFoundError is returned when a sandbox cannot be found.

func (*SandboxNotFoundError) Error

func (e *SandboxNotFoundError) Error() string

Error implements the error interface.

type SnapshotInfo

type SnapshotInfo struct {
	Names      []string `json:"names"`
	SnapshotID string   `json:"snapshotID"`
}

SnapshotInfo holds information about a sandbox snapshot.

type TimeoutError

type TimeoutError struct {
	Message string
}

TimeoutError is returned when an operation exceeds its deadline.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

type VolumeMount

type VolumeMount struct {
	Name string `json:"name,omitempty"`
	Path string `json:"path,omitempty"`
}

VolumeMount represents a mounted volume in the sandbox.

type WriteOption

type WriteOption interface {
	// contains filtered or unexported methods
}

WriteOption configures a Write, WriteBytes, or WriteString call.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) WriteOption

WithWriteTimeout overrides the HTTP timeout for a Write call.

Directories

Path Synopsis
examples
basic command
envvars command
files command
sandbox-info command
internal

Jump to

Keyboard shortcuts

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