Skip to main content
Read and write files inside a running sandbox over the same host-guest channel as command execution: no SSH, no network. See Filesystem for usage examples. For bulk file transfer, prefer a volume.

Typical flow

import m "github.com/superradcompany/microsandbox/sdk/go"

fs := sb.FS()                                                     // 1. get the accessor

err := fs.WriteString(ctx, "/tmp/config.json", `{"debug":true}`)  // 2. write
if err != nil {
    return err
}

content, err := fs.ReadString(ctx, "/tmp/config.json")            // 3. read back
if err != nil {
    return err
}
fmt.Println(content)

Methods

The accessor is obtained from a running sandbox via sb.FS(). Every method takes a context.Context first and returns an error (wrapped, inspectable with m.IsKind).

fs.Read()

func (fs *SandboxFSOps) Read(ctx context.Context, path string) ([]byte, error)
data, err := fs.Read(ctx, "/etc/hostname")
if err != nil {
    return err
}
fmt.Printf("%d bytes\n", len(data))
Read the entire contents of a file as raw bytes. The default FFI buffer is 1 MiB. For files larger than ~750 KiB (after base64 inflation), the runtime returns BufferTooSmall on the single-shot path, and this method transparently falls back to ReadStream. Callers get a uniform bytes-returning interface up to runtime memory limits.

Parameters

ctxcontext.Context
Cancels the read.
pathstring
Absolute path inside the guest, e.g. “/app/config.json”.

Returns

[]byte
File contents.

fs.ReadString()

func (fs *SandboxFSOps) ReadString(ctx context.Context, path string) (string, error)
content, err := fs.ReadString(ctx, "/tmp/config.json")
Read a file and return its contents as a string. The bytes are reinterpreted as UTF-8 without validation.

Parameters

ctxcontext.Context
Cancels the read.
pathstring
Absolute path inside the guest.

Returns

string
File contents.

fs.Write()

func (fs *SandboxFSOps) Write(ctx context.Context, path string, data []byte) error
err := fs.Write(ctx, "/tmp/data.bin", []byte{0x00, 0x01, 0x02})
Write bytes to a file, creating it if it does not exist and truncating it if it does.

Parameters

ctxcontext.Context
Cancels the write.
pathstring
Absolute path inside the guest.
data[]byte
Bytes to write.

fs.WriteString()

func (fs *SandboxFSOps) WriteString(ctx context.Context, path, content string) error
err := fs.WriteString(ctx, "/tmp/hello.txt", "hi")
Write a UTF-8 string to a file. Convenience wrapper over Write.

Parameters

ctxcontext.Context
Cancels the write.
pathstring
Absolute path inside the guest.
contentstring
Text to write.

fs.List()

func (fs *SandboxFSOps) List(ctx context.Context, path string) ([]FsEntry, error)
entries, err := fs.List(ctx, "/etc")
if err != nil {
    return err
}
for _, e := range entries {
    fmt.Printf("%s (%s, %d bytes)\n", e.Path, e.Kind, e.Size)
}
List the entries in a directory inside the sandbox.

Parameters

ctxcontext.Context
Cancels the listing.
pathstring
Absolute directory path inside the guest.

Returns

Directory entries.

fs.Stat()

func (fs *SandboxFSOps) Stat(ctx context.Context, path string) (*FsStat, error)
st, err := fs.Stat(ctx, "/etc/hosts")
if err != nil {
    return err
}
fmt.Printf("%d bytes, dir=%v\n", st.Size, st.IsDir)
Get detailed metadata for a file or directory.

Parameters

ctxcontext.Context
Cancels the stat.
pathstring
Absolute path inside the guest.

Returns

File metadata.

fs.Mkdir()

func (fs *SandboxFSOps) Mkdir(ctx context.Context, path string) error
err := fs.Mkdir(ctx, "/app/cache/sessions")
Create a directory and any missing parents inside the sandbox.

Parameters

ctxcontext.Context
Cancels the operation.
pathstring
Absolute directory path inside the guest.

fs.Remove()

func (fs *SandboxFSOps) Remove(ctx context.Context, path string) error
err := fs.Remove(ctx, "/tmp/scratch.txt")
Delete a single file. Use RemoveDir for directories.

Parameters

ctxcontext.Context
Cancels the operation.
pathstring
Absolute file path inside the guest.

fs.RemoveDir()

func (fs *SandboxFSOps) RemoveDir(ctx context.Context, path string) error
err := fs.RemoveDir(ctx, "/app/cache")
Remove a directory recursively.

Parameters

ctxcontext.Context
Cancels the operation.
pathstring
Absolute directory path inside the guest.

fs.Copy()

func (fs *SandboxFSOps) Copy(ctx context.Context, src, dst string) error
err := fs.Copy(ctx, "/etc/hosts", "/tmp/hosts.bak")
Copy a file within the sandbox.

Parameters

ctxcontext.Context
Cancels the operation.
srcstring
Source path inside the guest.
dststring
Destination path inside the guest.

fs.Rename()

func (fs *SandboxFSOps) Rename(ctx context.Context, src, dst string) error
err := fs.Rename(ctx, "/tmp/old.log", "/tmp/archive/old.log")
Rename or move a file or directory within the sandbox.

Parameters

ctxcontext.Context
Cancels the operation.
srcstring
Current path inside the guest.
dststring
New path inside the guest.

fs.Exists()

func (fs *SandboxFSOps) Exists(ctx context.Context, path string) (bool, error)
ok, err := fs.Exists(ctx, "/app/.initialized")
if err != nil {
    return err
}
if !ok {
    // first boot
}
Report whether a file or directory exists at the given path.

Parameters

ctxcontext.Context
Cancels the check.
pathstring
Absolute path inside the guest.

Returns

bool
true if the path exists.

fs.CopyFromHost()

func (fs *SandboxFSOps) CopyFromHost(ctx context.Context, hostPath, guestPath string) error
err := fs.CopyFromHost(ctx, "./seed.db", "/app/data/seed.db")
Copy a file from the host machine into the sandbox. For transferring many files, consider a bind-mounted volume instead.

Parameters

ctxcontext.Context
Cancels the copy.
hostPathstring
Source path on the host.
guestPathstring
Destination path inside the guest.

fs.CopyToHost()

func (fs *SandboxFSOps) CopyToHost(ctx context.Context, guestPath, hostPath string) error
err := fs.CopyToHost(ctx, "/app/output/report.csv", "./report.csv")
Copy a file from the sandbox to the host machine.

Parameters

ctxcontext.Context
Cancels the copy.
guestPathstring
Source path inside the guest.
hostPathstring
Destination path on the host.

fs.ReadStream()

func (fs *SandboxFSOps) ReadStream(ctx context.Context, path string) (*FsReadStream, error)
rs, err := fs.ReadStream(ctx, "/var/log/syslog")
if err != nil {
    return err
}
defer rs.Close()

for {
    chunk, err := rs.Recv(ctx)
    if err != nil {
        return err
    }
    if chunk == nil {
        break // EOF
    }
    os.Stdout.Write(chunk)
}

// Or drain it as an io.WriterTo.
_, err = rs.WriteTo(os.Stdout)
Open a streaming reader for a file. Use this for files too large to fit in memory; data is delivered in chunks. The caller must Close the returned *FsReadStream. Read falls back to this automatically when a file exceeds the single-shot buffer.

Parameters

ctxcontext.Context
Cancels opening the stream.
pathstring
Absolute path inside the guest.

Returns

Open read stream; close it when done.

fs.WriteStream()

func (fs *SandboxFSOps) WriteStream(ctx context.Context, path string) (*FsWriteStream, error)
ws, err := fs.WriteStream(ctx, "/tmp/big.bin")
if err != nil {
    return err
}

if _, err := ws.Write(largeChunk); err != nil {
    return err
}
if err := ws.Close(ctx); err != nil {
    return err
}
Open a streaming writer for a file. Use this for files too large to fit in memory. The caller must call Close(ctx) on the returned *FsWriteStream to finalise the write.

Parameters

ctxcontext.Context
Cancels opening the stream.
pathstring
Absolute path inside the guest.

Returns

Open write stream; Close(ctx) it to finalise.

Types

FsEntry

Returned by List()

A single directory listing entry.
FieldTypeDescription
PathstringFile path
KindFsEntryKindEntry type
Sizeint64File size in bytes
Modeuint32Unix permission bits

FsEntryKind

Used by FsEntry.Kind

Classifies a directory listing entry. Defined as type FsEntryKind string.
ConstantValueDescription
FsEntryKindFile"file"Regular file
FsEntryKindDirectory"directory"Directory
FsEntryKindSymlink"symlink"Symbolic link
FsEntryKindOther"other"Other entry type

FsStat

Returned by Stat()

Detailed file metadata.
FieldTypeDescription
PathstringFile path
Sizeint64File size in bytes
Modeuint32Unix permission bits
ModTimetime.TimeLast modified timestamp; zero value if the guest did not report one
IsDirboolWhether the path is a directory

FsReadStream

Returned by ReadStream()

An open streaming read from a guest file. Must be closed with Close when done.
MethodReturnsDescription
Recv(ctx context.Context)([]byte, error)Receive the next chunk; returns (nil, nil) at EOF
WriteTo(w io.Writer)(int64, error)Drain the stream into w using context.Background(); implements io.WriterTo
CopyTo(ctx context.Context, w io.Writer)(int64, error)Drain into w honouring ctx for per-chunk cancellation
Close()errorRelease the read stream handle
On a write error or partial write, WriteTo and CopyTo return the partial byte count and leave the stream open so the caller can recover; close it explicitly in either case.

FsWriteStream

Returned by WriteStream()

An open streaming write to a guest file. Must be closed with Close(ctx) to finalise the write.
MethodReturnsDescription
Write(p []byte)(int, error)Send a chunk; implements io.Writer, uses context.Background() internally
WriteCtx(ctx context.Context, data []byte)errorSend a chunk with explicit context control
Close(ctx context.Context)errorSend the EOF marker and wait for the guest to confirm; must be called to complete the write