Skip to content

Storage Library for Go ​

storage logo

A fast, ergonomic, multi-driver storage library for Go.

Go ReferenceLicense: MITCIGo versionLatest tagPublished GitHub release count

Quick Start · Install · Drivers · Transfers · Signed Requests · Testing · Benchmarks · API · Development

Read, write, and list files through one Go interface. Choose a driver for each disk. Use a local directory for development, or a remote backend such as S3 for shared storage. Use a manager when backups, uploads, and assets need separate disks.

Quickstart ​

Write and read a file on a local disk. Open an existing Go module that uses Go 1.25.0 or newer, then add Storage and the local driver.

sh
go get github.com/goforj/storage github.com/goforj/storage/driver/localstorage
go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/goforj/storage"
	"github.com/goforj/storage/driver/localstorage"
)

func main() {
	ctx := context.Background()

	// The local driver creates the root directory if needed.
	disk, err := storage.Build(ctx, localstorage.Config{Root: "./data"})
	if err != nil {
		log.Fatalf("open local disk: %v", err)
	}
	defer disk.Close()

	// Paths are relative to the disk root, so this file lives under ./data.
	const path = "notes/hello.txt"
	if err := disk.Put(ctx, path, []byte("hello from storage")); err != nil {
		log.Fatalf("write %s: %v", path, err)
	}

	body, err := disk.Get(ctx, path)
	if err != nil {
		log.Fatalf("read %s: %v", path, err)
	}
	fmt.Println(string(body))
	// Output: hello from storage
}

Copy, move, and delete ​

Add these calls at the end of main.

go
// Work on a copy so the original stays in notes.
if err := disk.Copy(ctx, "notes/hello.txt", "notes/hello-copy.txt"); err != nil {
	log.Fatal(err)
}
if err := disk.Move(ctx, "notes/hello-copy.txt", "archive/hello.txt"); err != nil {
	log.Fatal(err)
}

// Read from the destination to verify the move before cleanup.
archived, err := disk.Get(ctx, "archive/hello.txt")
if err != nil {
	log.Fatal(err)
}
fmt.Println("Archived copy:", string(archived))
// Output: Archived copy: hello from storage

if err := disk.Delete(ctx, "archive/hello.txt"); err != nil {
	log.Fatal(err)
}

Run the same backup job on a local disk or on RustFS through the S3 driver.

Install ​

Add the Storage module and the driver you use. For S3, run the following command in your Go module.

sh
go get github.com/goforj/storage github.com/goforj/storage/driver/s3storage

Driver Matrix ​

All drivers read and write byte slices. S3 and Azure Blob also support streaming objects. Select a driver badge for its configuration reference.

DriverUse it forFile copyFile or directory moveAccess URL
localFiles on a local or mounted filesystemStreamed, atomic replaceNative renameUnsupported
memoryIn-process storage and application testsIn-memory cloneAtomic rekey for files. Directories use copy, then content-checked delete.Unsupported
redisSmall blobs shared across processesWhole value, transactionalTransactional for files. Directories use copy, then revision-checked delete.Unsupported
ftpExisting FTP serversStreamed, staged uploadServer renameUnsupported
sftpFile transfers over SSHStreamed, atomic replacePOSIX renameUnsupported
s3Amazon S3 and compatible stores such as RustFSServer-side, preserves metadataCopy, then ETag-checked deleteSigned GET, 15 min
gcsGoogle Cloud Storage bucketsServer-side, preserves metadataCopy, then generation-checked deleteSigned GET, 15 min on GCS
azureblobAzure Blob Storage containersStreamed, preserves portable metadataCopy, then ETag-checked deleteRead SAS, 15 min with account key
smbDirect connections to Windows and NAS file sharesStreamed, staged replacementServer renameUnsupported
dropboxDropbox files and foldersBuffered download and uploadProvider moveTemporary file link
googledriveGoogle Drive folders and Shared DrivesProvider copy, unused destinationRename or reparent by IDUnsupported
onedriveOneDrive and SharePoint document librariesBuffered download and uploadRename or reparent by IDUnsupported
webdavWebDAV collections such as NextcloudServer COPY, unused destinationServer MOVEUnsupported
rcloneAny configured Rclone remote, subject to its capabilitiesProvider-native or streamedCopy, then delete for files. Directories use copy, then content-checked delete.Remote-dependent

If a backend would benefit from a first-class driver, open an issue and tell us what you need it to support. For other backends, see the full list of Rclone backends. See the inline Rclone example for a local write and read.

Directory deletion

  • Dropbox, Google Drive, OneDrive, and WebDAV return ErrUnsupported.
  • S3, GCS, and Azure Blob delete only empty directory markers.
  • Other drivers delete empty directories. Rclone depends on the remote.

Transfer files ​

Use storage.WriteStream to write from an io.Reader to a local, S3, GCS, or Azure Blob disk. The caller closes the reader. The stream can have an unknown length. The write replaces the destination after the reader reaches EOF.

The CSV import example streams an HTTP response into S3. To run it, start the RustFS service from the backup example. Run go run ./import_csv <export-url> from examples with a working HTTP export URL. The command writes the response to exports/orders.csv.

When the source is another disk, pass both disks to storage.CopyFile. The source must support streaming reads. The destination must support streaming writes. The copy transfers file contents, replaces an existing destination, and keeps the source.

go
err := storage.CopyFile(ctx, local, "exports/orders.csv", archive, "orders.csv")

S3 buffers small files in 64 KiB and uses 16 MiB parts for larger streams, up to 10,000 parts. GCS uses 4 MiB resumable chunks. Azure Blob uses 4 MiB blocks, up to 50,000 blocks. Use the sized object API on Azure Blob when you need larger blocks.

Move or delete a listed S3 entry ​

S3 can store a file named reports alongside the folder reports/. When an application acts on a row from a cursor page, pass the row's storage.Entry to storage.MoveEntry or storage.DeleteEntry. The entry's kind selects the file or folder at that path.

go
err := storage.MoveEntry(ctx, disk, entry, "archive/reports")

Move a directory to an unused destination and keep exclusive access to that destination until the move completes. DeleteEntry deletes files and empty directory markers. A directory with children returns storage.ErrForbidden. An object with data at a trailing-slash key returns storage.ErrUnsupported during a directory move or deletion.

S3 directory markers require a backend that supports conditional writes and deletes. MakeDir returns storage.ErrConflict if the marker key already contains data. Deleting a marker whose ETag changed also returns storage.ErrConflict. On Amazon S3, grant s3:GetObject, s3:PutObject, and s3:DeleteObject for the marker keys used by these operations.

Sign requests for clients ​

On S3, use storage.SignDownload or storage.SignUpload when a client needs temporary access to one object. Pass the TTL in whole seconds, from one second to seven days. Temporary credentials can expire sooner. Send the returned URL, method, and headers to the client.

go
upload, err := storage.SignUpload(ctx, disk, "incoming/report.csv", 5*time.Minute)

The upload request can replace an existing object at that path. Choose the path and authorize the caller before signing. For browser uploads, configure the bucket's CORS policy to allow the app's origin, the returned method, and any signed headers.

Testing with fakes ​

Pass storagetest.Fake(t) to the code under test. Use AssertExists, AssertMissing, or AssertContents to check what it wrote. Use storagetest.FakeManager when the code selects a disk by name.

go
func TestWriteNote(t *testing.T) {
	disk := storagetest.Fake(t)
	if err := disk.Put(t.Context(), "notes/hello.txt", []byte("hello from storage")); err != nil {
		t.Fatal(err)
	}

	storagetest.AssertContents(t, disk, "notes/hello.txt", []byte("hello from storage"))
}

Benchmarks ​

Copy results and benchmark charts

8 MiB copy on local benchmark fixtures

Fixturems/opKiB allocated/opAllocations/op
local8.85135.989.1
memory0.2898192.611.0
rclone_local11.66875.5146.4
ftp2.770100.1422.1
sftp85.93019702.56542.2
redis5.7948211.6241.0
gcs12.03616791.01208.4
s332.22178.6934.4
rclone_s367.041126.91573.0

Storage benchmark latency chart

Storage benchmark allocated bytes chart

Storage benchmark allocation count chart

Storage benchmark iteration chart

Upgrading to v0.13 ​

Pass a context to constructors and operations. Replace storage.BuildContext(ctx, cfg) with storage.Build(ctx, cfg) and disk.WithContext(ctx).Get(path) with disk.Get(ctx, path). Close standalone disks with disk.Close() and manager-owned disks with manager.Close(). See the v0.13.0 upgrade notes for custom drivers and streaming.

Cursor pagination ​

Use storage.CursorStorage on S3 or Google Cloud Storage (GCS) to list immediate children one backend page at a time. Start with an empty cursor. Pass NextCursor back with the same disk and path until it is empty.

go
pager, ok := disk.(storage.CursorStorage)
if !ok {
	return storage.ErrUnsupported
}

for cursor := ""; ; {
	page, err := pager.ListCursorPage(ctx, "reports", cursor, 50)
	if err != nil {
		return err
	}
	for _, entry := range page.Entries {
		fmt.Println(entry.Path)
	}
	if page.NextCursor == "" {
		break
	}
	cursor = page.NextCursor
}

S3 and GCS accept limits from 1 to 1,000. The provider can return a short or empty page with a continuation token. Use the cursor to detect the last page. A file and directory with the same path can appear separately. Each page reflects the live listing.

API reference ​

See the package documentation for the full API.

API Index ​

GroupFunctions
FilesDelete · Get · Move · Put · URL
DirectoriesCountFiles · PagedStorage.ListPage · PaginateEntries · List · Walk
ConstructionBuild
ManagerNew
StreamingGetWithLimit · Objects
PathsJoinPrefix · NormalizePath
Driver Constructorsazureblob · dropbox · ftp · gcs · googledrive · local · memory · onedrive · rclone · redis · s3 · s3storage.PrepareBucket · sftp · smb · webdav
Rclone ConfigRenderLocal · RenderS3

Files ​

Storage.Delete ​

Delete removes the object at path.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
const path = "docs/readme.txt"
if err := disk.Put(context.Background(), path, []byte("hello")); err != nil {
	log.Fatalf("write file: %v", err)
}
if err := disk.Delete(context.Background(), path); err != nil {
	log.Fatalf("delete file: %v", err)
}

exists, err := disk.Exists(context.Background(), path)
if err != nil {
	log.Fatalf("check whether file exists: %v", err)
}
fmt.Println(exists)
// Output: false

Storage.Get ​

Get reads the object at path.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

ctx, cancel := context.WithCancel(context.Background())
cancel()

_, err = disk.Get(ctx, "docs/readme.txt")
fmt.Println(errors.Is(err, context.Canceled))
// Output: true

Storage.Move ​

Move moves the object or directory tree at src to dst.

For directory moves implemented as copy and delete, reserve the destination for the move. If copying fails, the driver rolls back entries it copied. If source deletion fails, the complete destination and some source entries can both remain.

Pause writes to the source during Rclone moves. Rclone checks the source before deleting it in a separate step. If it detects a change, it returns ErrConflict and keeps the changed source.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
if err := disk.Put(context.Background(), "docs/readme.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}

if err := disk.Move(context.Background(), "docs/readme.txt", "archive/readme.txt"); err != nil {
	log.Fatal(err)
}
data, err := disk.Get(context.Background(), "archive/readme.txt")
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(data))
// Output: hello

Storage.Put ​

Put writes an object at path, overwriting any existing object.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
if err := disk.Put(context.Background(), "docs/readme.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}

entry, err := disk.Stat(context.Background(), "docs/readme.txt")
if err != nil {
	log.Fatal(err)
}
fmt.Println(entry.Path, entry.Size)
// Output: docs/readme.txt 5

Storage.URL ​

URL returns a usable access URL when the driver supports it.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}

if err := disk.Put(context.Background(), "docs/readme.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}

_, err = disk.URL(context.Background(), "docs/readme.txt")
fmt.Println("URL unsupported:", errors.Is(err, storage.ErrUnsupported))
// Output: URL unsupported: true

Directories ​

CountFiles ​

CountFiles returns the recursive count of non-directory entries under path.

CountFiles uses Walk under the hood, so it works across drivers that support recursive traversal.

go
ctx := context.Background()
disk, err := storage.Build(ctx, memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

if err := disk.Put(ctx, "docs/readme.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}
if err := disk.Put(ctx, "docs/archive/guide.txt", []byte("guide")); err != nil {
	log.Fatal(err)
}

total, err := storage.CountFiles(ctx, disk, "docs")
if err != nil {
	log.Fatal(err)
}
fmt.Println(total)
// Output: 2

PagedStorage.ListPage ​

ListPage returns one page of immediate children under path.

The limit bounds the returned entries. Most drivers fetch the full current listing on each call. Use cursor pagination for immediate children on S3 and GCS, or WalkObjects on S3 and Azure Blob for a flat object listing.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
if err := disk.Put(context.Background(), "docs/a.txt", []byte("a")); err != nil {
	log.Fatal(err)
}
if err := disk.Put(context.Background(), "docs/b.txt", []byte("b")); err != nil {
	log.Fatal(err)
}
paged, ok := disk.(storage.PagedStorage)
if !ok {
	log.Fatal("disk does not support pagination")
}

for offset := 0; ; {
	page, err := paged.ListPage(context.Background(), "docs", offset, 1)
	if err != nil {
		log.Fatal(err)
	}
	for _, entry := range page.Entries {
		fmt.Println(entry.Path)
		// Output:
		// docs/a.txt
		// docs/b.txt
	}
	if !page.HasMore {
		break
	}
	offset += len(page.Entries)
}

PaginateEntries ​

PaginateEntries returns a clamped page without mutating the caller's entry slice.

go
entries := []storage.Entry{{Path: "a.txt"}, {Path: "b.txt"}, {Path: "c.txt"}}
page := storage.PaginateEntries(entries, 1, 1)
fmt.Println(page.Entries[0].Path, page.HasMore)
// Output: b.txt true

Storage.List ​

List returns immediate children sorted by path. Pass an empty path to list the disk root.

Each entry path is relative to the disk root. Use Walk to visit descendants.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
if err := disk.Put(context.Background(), "docs/readme.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}

entries, err := disk.List(context.Background(), "docs")
if err != nil {
	log.Fatal(err)
}
for _, entry := range entries {
	fmt.Println(entry.Path)
}
// Output: docs/readme.txt

Storage.Walk ​

Walk visits entries recursively in deterministic path order.

go
disk, err := storage.Build(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
if err := disk.Put(context.Background(), "docs/archive/guide.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}

if err := disk.Walk(context.Background(), "docs", func(entry storage.Entry) error {
	fmt.Println(entry.Path)
	// Output:
	// docs/archive
	// docs/archive/guide.txt
	return nil
}); err != nil {
	log.Fatal(err)
}

Construction ​

Build ​

Build opens a standalone disk using ctx for setup.

go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
disk, err := storage.Build(ctx, memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

if err := disk.Put(ctx, "notes/hello.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}

Manager ​

New ​

New opens the configured disks. Set Default to one of their names and call manager.Close() at shutdown to close them all.

go
manager, err := storage.New(context.Background(), storage.Config{
	Default: "scratch",
	Disks: map[storage.DiskName]storage.DriverConfig{
		"scratch": memorystorage.Config{},
		"uploads": memorystorage.Config{},
	},
})
if err != nil {
	log.Fatal(err)
}
uploads, err := manager.Disk("uploads")
if err != nil {
	log.Fatal(err)
}

if err := uploads.Put(context.Background(), "notes/hello.txt", []byte("hello")); err != nil {
	log.Fatal(err)
}
// Both disks use the same path without sharing files.
exists, err := manager.Default().Exists(context.Background(), "notes/hello.txt")
if err != nil {
	log.Fatal(err)
}
fmt.Println("On the default disk:", exists)
// Output: On the default disk: false

if err := manager.Close(); err != nil {
	log.Fatal(err)
}

Streaming ​

GetWithLimit ​

GetWithLimit reads a file into memory with a caller-supplied byte limit. It returns ErrTooLarge and no data if the file exceeds the limit. A zero limit accepts only an empty file. Drivers without streaming reads return ErrUnsupported.

Local, S3, GCS, and Azure Blob support bounded reads and storage.ReadStream. All four also support storage.WriteStream and commit the replacement after the stream reaches EOF.

See the local streaming example for a write and read.

Objects ​

Objects returns a driver's streaming object capability. Each streaming call takes its own context. Unsupported drivers return ErrUnsupported.

Download with OpenObject and close the returned reader. Upload with PutObject and pass the reader's exact byte count. WalkObjects visits objects one provider page at a time. For a direct driver handle, call storagecore.Objects.

Use the backup example to start RustFS before running this upload.

go
// Run the RustFS backup demo first to create the bucket.
ctx := context.Background()
disk, err := storage.Build(ctx, s3storage.Config{
	Bucket:          "storage-demo",
	Region:          "us-east-1",
	Endpoint:        "http://127.0.0.1:19000",
	UsePathStyle:    true,
	AccessKeyID:     "storage-demo",
	SecretAccessKey: "storage-demo-password",
})
if err != nil {
	log.Fatalf("build S3 disk: %v", err)
}
objects, err := storage.Objects(disk)
if err != nil {
	log.Fatalf("open object streaming API: %v", err)
}
body := strings.NewReader("hello from storage")
info, err := objects.PutObject(ctx, "stream.txt", body, storagecore.PutObjectOptions{
	Size: body.Size(),
})
if err != nil {
	log.Fatalf("upload object: %v", err)
}
fmt.Println(info.Key, info.Size)
// Output: stream.txt 18

Paths ​

JoinPrefix ​

JoinPrefix combines a disk prefix with a path using slash separators.

go
fmt.Println(storage.JoinPrefix("assets", "logo.svg"))
// Output: assets/logo.svg

NormalizePath ​

NormalizePath cleans a user path, normalizes separators, and rejects attempts to escape the disk root or prefix root.

The empty string and root-like inputs normalize to the logical root.

go
path, err := storage.NormalizePath(" /avatars//user-1.png ")
if err != nil {
	log.Fatal(err)
}
fmt.Println(path)
// Output: avatars/user-1.png

Driver Constructors ​

azureblobstorage.New ​

New prepares a client without contacting Azure or creating a container.

The container must already exist. Use AccountURL for Azure Identity or ConnectionString for Azurite or account-key authentication. Signed read URLs require an account key.

go
disk, err := azureblobstorage.New(context.Background(), azureblobstorage.Config{
	Container:       "backups",
	ConnectionString: os.Getenv("AZURE_STORAGE_CONNECTION_STRING"),
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

dropboxstorage.New ​

New prepares a Dropbox disk using an access token.

go
disk, err := dropboxstorage.New(context.Background(), dropboxstorage.Config{
	Token: os.Getenv("DROPBOX_ACCESS_TOKEN"),
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

ftpstorage.New ​

New connects to an existing FTP server using the supplied credentials.

Enable StagedWrites to publish uploads by rename. This requires server support and rename permission. Interrupted direct uploads can leave a partial file.

go
disk, err := ftpstorage.New(context.Background(), ftpstorage.Config{
	Host:     "files.example.com",
	User:     "backups",
	Password: os.Getenv("FTP_PASSWORD"),
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

gcsstorage.New ​

New opens a GCS disk for an existing bucket. This example uses Google Application Default Credentials.

go
disk, err := gcsstorage.New(context.Background(), gcsstorage.Config{
	Bucket: "uploads",
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

googledrivestorage.New ​

New prepares a Google Drive disk that calls your token source for each request.

Set SharedDriveID for a Shared Drive. Reuse one disk handle to coordinate writes to the same path, or coordinate writers across separate handles in your application.

go
disk, err := googledrivestorage.New(context.Background(), googledrivestorage.Config{
	FolderID: "backup-folder-id",
	TokenSource: func(context.Context) (string, error) {
		return os.Getenv("GOOGLE_DRIVE_ACCESS_TOKEN"), nil
	},
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

localstorage.New ​

New constructs local storage rooted at cfg.Root with an optional prefix.

Use BufferedWrites for data you can recreate. Replacement stays atomic, but a crash can lose a write that already returned successfully.

go
disk, err := localstorage.New(context.Background(), localstorage.Config{
	Root:   "./data",
	Prefix: "sandbox",
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

memorystorage.New ​

New constructs in-memory storage.

go
disk, err := memorystorage.New(context.Background(), memorystorage.Config{})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

onedrivestorage.New ​

New prepares a disk using a caller-managed Graph credential.

Use the document library's drive ID for SharePoint. An empty DriveID selects the signed-in user's OneDrive. Uploads and copies are limited to 250 MB.

go
disk, err := onedrivestorage.New(context.Background(), onedrivestorage.Config{
	DriveID: "document-library-id",
	TokenSource: func(context.Context) (string, error) {
		return os.Getenv("ONEDRIVE_ACCESS_TOKEN"), nil
	},
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

rclonestorage.New ​

New opens an Rclone remote. All disks in a process share one Rclone configuration. Define the backups remote before opening this disk.

go
disk, err := rclonestorage.New(context.Background(), rclonestorage.Config{
	Remote: "backups:archive",
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

redisstorage.New ​

New constructs Redis-backed storage using go-redis.

When upgrading from v0.4.6 or earlier, stop all clients sharing a database and prefix, upgrade them together, then restart them. Older clients cannot read the new index.

go
disk, err := redisstorage.New(context.Background(), redisstorage.Config{
	Addr:   "127.0.0.1:6379",
	Prefix: "scratch",
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

s3storage.New ​

New prepares an S3 disk for an existing bucket. This example uses the default AWS credential chain.

go
disk, err := s3storage.New(context.Background(), s3storage.Config{
	Bucket: "uploads",
	Region: "us-east-1",
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

s3storage.PrepareBucket ​

PrepareBucket creates a missing bucket using the same configuration and credentials as the driver. Existing buckets are unchanged. Permission failures never trigger a creation attempt.

go
// Start the backup demo's RustFS container before running this example.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

cfg := s3storage.Config{
	Bucket:          "storage-demo",
	Region:          "us-east-1",
	Endpoint:        "http://127.0.0.1:19000",
	UsePathStyle:    true,
	AccessKeyID:     "storage-demo",
	SecretAccessKey: "storage-demo-password",
}
if err := s3storage.PrepareBucket(ctx, cfg); err != nil {
	log.Fatalf("prepare S3 bucket: %v", err)
}
fmt.Println("bucket ready")
// Output: bucket ready

sftpstorage.New ​

New connects to an SFTP server and verifies its host key. Set SFTP_KEY_PATH to your private key file and SFTP_KNOWN_HOSTS to a known_hosts file that contains the server's key.

After canceling a write, let cleanup finish before closing the disk. A .storage-tmp- file may remain if cleanup cannot reach the server.

go
disk, err := sftpstorage.New(context.Background(), sftpstorage.Config{
	Host:           "files.example.com",
	User:           "backups",
	KeyPath:        os.Getenv("SFTP_KEY_PATH"),
	KnownHostsPath: os.Getenv("SFTP_KNOWN_HOSTS"),
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

smbstorage.New ​

New opens a signed SMB session. Close the returned disk when it is no longer needed.

The server must support signing over SMB 2 or 3. Grant the account access on both the share and the filesystem.

go
disk, err := smbstorage.New(context.Background(), smbstorage.Config{
	Address:  "fileserver.example.com",
	Share:    "backups",
	User:     "storage",
	Password: os.Getenv("SMB_PASSWORD"),
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

webdavstorage.New ​

New prepares a WebDAV disk at an existing collection URL.

Copy and move require an unused destination. File deletion requires a strong ETag and support for If-Match.

go
disk, err := webdavstorage.New(context.Background(), webdavstorage.Config{
	Endpoint: "https://files.example.com/remote.php/dav/files/backups/",
	User:     "backups",
	Password: os.Getenv("WEBDAV_PASSWORD"),
})
if err != nil {
	log.Fatal(err)
}
defer disk.Close()

Rclone Config ​

rclonestorage.RenderLocal ​

RenderLocal returns ini-formatted rclone config for a local backend.

go
cfg, err := rclonestorage.RenderLocal(rclonestorage.LocalRemote{Name: "local"})
if err != nil {
	log.Fatal(err)
}
fmt.Print(cfg)
// Output:
// [local]
// type = local

rclonestorage.RenderS3 ​

RenderS3 returns ini-formatted rclone config content for a single S3 remote.

go
cfg, err := rclonestorage.RenderS3(rclonestorage.S3Remote{
	Name:            "assets",
	Region:          "us-east-1",
	AccessKeyID:     "example-key",
	SecretAccessKey: "example-secret",
})
if err != nil {
	log.Fatal(err)
}

// Show the remote name without logging credentials.
header, _, _ := strings.Cut(cfg, "\n")
fmt.Println(header)
// Output: [assets]

Development ​

sh
make test                         # Test the root module
make test-examples                # Test the examples module
make test-integration             # Test all driver fixtures with Docker
make test-integration gcs         # Test GCS with its emulator
make test-coverage                # Generate combined coverage
go run ./docs/examplegen/main.go  # Regenerate the runnable examples
go run ./docs/readme/main.go      # Regenerate the API reference
make docs-watch                   # Regenerate docs and examples as code changes

Run go test ./... in each driver module you change. See make help for all targets, the test plan for fixture details, and the release runbook for publishing.

Using with GoForj ​

GoForj Apps expose named disks through generated accessors. Use those accessors in application services and keep backend selection in storage configuration.

For the App workflow, see Storage Patterns.