s3fs

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2025 License: MIT Imports: 16 Imported by: 0

README

S3FS - S3 FileSystem

Go Reference Go Report Card CI License

The s3fs package implements an absfs.Filer for S3-compatible object storage. It provides file operations on S3 buckets using the AWS SDK v2.

Features

  • S3-compatible storage: Works with AWS S3 and compatible services
  • Standard interface: Implements absfs.Filer for seamless integration
  • Basic operations: Read, write, delete files in S3 buckets

Install

go get github.com/absfs/s3fs

Example Usage

Basic Usage
package main

import (
    "log"
    "os"

    "github.com/absfs/s3fs"
)

func main() {
    // Create S3 filesystem
    fs, err := s3fs.New(&s3fs.Config{
        Bucket: "my-bucket",
        Region: "us-east-1",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Write a file
    f, _ := fs.OpenFile("path/to/file.txt", os.O_CREATE|os.O_WRONLY, 0644)
    f.Write([]byte("Hello, S3!"))
    f.Close()

    // Read a file
    f, _ = fs.OpenFile("path/to/file.txt", os.O_RDONLY, 0)
    defer f.Close()

    buf := make([]byte, 1024)
    n, _ := f.Read(buf)
    log.Printf("Read: %s", buf[:n])

    // Delete a file
    fs.Remove("path/to/file.txt")
}
With Custom AWS Config
package main

import (
    "context"
    "log"

    "github.com/absfs/s3fs"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/credentials"
)

func main() {
    // Load custom AWS config
    cfg, err := config.LoadDefaultConfig(context.TODO(),
        config.WithRegion("us-west-2"),
        config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
            "access-key",
            "secret-key",
            "",
        )),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Create S3 filesystem with custom config
    fs, err := s3fs.New(&s3fs.Config{
        Bucket: "my-bucket",
        Config: &cfg,
    })
    if err != nil {
        log.Fatal(err)
    }

    // Use filesystem
}

Limitations

  • Chmod, Chtimes, Chown: Not supported (S3 doesn't have POSIX permissions)
  • Directories: Represented as zero-byte objects with trailing slash
  • Seeking: Limited support (S3 is object storage, not a traditional filesystem)
  • Atomic operations: Some operations (like Rename) require copy+delete

Authentication

The filesystem uses the AWS SDK's default credential chain, which checks:

  1. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
  2. Shared credentials file (~/.aws/credentials)
  3. IAM role (when running on EC2, ECS, Lambda, etc.)

absfs

Check out the absfs repo for more information about the abstract filesystem interface and features like filesystem composition.

LICENSE

This project is governed by the MIT License. See LICENSE

Documentation

Overview

Package s3fs implements an absfs.Filer for S3-compatible object storage. It provides file operations on S3 buckets using the AWS SDK v2.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Bucket string      // S3 bucket name
	Region string      // AWS region
	Config *aws.Config // Optional AWS config (if nil, uses default config loading)
}

Config contains the configuration for connecting to S3.

type File

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

File represents a file in S3.

func (*File) Close

func (f *File) Close() error

Close closes the file and uploads to S3 if writing.

func (*File) Name

func (f *File) Name() string

Name returns the name of the file.

func (*File) Read

func (f *File) Read(b []byte) (int, error)

Read reads from the S3 object.

func (*File) ReadAt

func (f *File) ReadAt(b []byte, off int64) (int, error)

ReadAt reads from the S3 object at a specific offset.

func (*File) ReadDir

func (f *File) ReadDir(n int) ([]iosfs.DirEntry, error)

ReadDir reads the contents of the directory and returns a slice of up to n DirEntry values.

func (*File) Readdir

func (f *File) Readdir(n int) ([]os.FileInfo, error)

Readdir reads directory entries (lists objects with prefix).

func (*File) Readdirnames

func (f *File) Readdirnames(n int) ([]string, error)

Readdirnames reads directory entry names.

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (int64, error)

Seek seeks within the file.

func (*File) Stat

func (f *File) Stat() (os.FileInfo, error)

Stat returns file info.

func (*File) Sync

func (f *File) Sync() error

Sync is a no-op for S3 (writes are synchronous).

func (*File) Truncate

func (f *File) Truncate(size int64) error

Truncate truncates the file.

func (*File) Write

func (f *File) Write(b []byte) (int, error)

Write writes to the file buffer (will be uploaded on Close).

func (*File) WriteAt

func (f *File) WriteAt(b []byte, off int64) (int, error)

WriteAt writes to the buffer at a specific offset.

func (*File) WriteString

func (f *File) WriteString(s string) (int, error)

WriteString writes a string to the file.

type FileSystem

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

FileSystem implements absfs.Filer for S3 object storage.

func New

func New(cfg *Config) (*FileSystem, error)

New creates a new S3 filesystem with the given configuration.

func NewWithClient

func NewWithClient(client S3Client, bucket string) *FileSystem

NewWithClient creates a new S3 filesystem with a custom S3 client. This is primarily useful for testing with mock clients.

func NewWithClientAndContext

func NewWithClientAndContext(ctx context.Context, client S3Client, bucket string) *FileSystem

NewWithClientAndContext creates a new S3 filesystem with a custom S3 client and context.

func (*FileSystem) Chmod

func (fs *FileSystem) Chmod(name string, mode os.FileMode) error

Chmod is not supported for S3.

func (*FileSystem) Chown

func (fs *FileSystem) Chown(name string, uid, gid int) error

Chown is not supported for S3.

func (*FileSystem) Chtimes

func (fs *FileSystem) Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes is not supported for S3.

func (*FileSystem) Mkdir

func (fs *FileSystem) Mkdir(name string, perm os.FileMode) error

Mkdir creates a "directory" in S3 (creates a zero-byte object with trailing slash).

func (*FileSystem) OpenFile

func (fs *FileSystem) OpenFile(name string, flag int, perm os.FileMode) (absfs.File, error)

OpenFile opens a file in S3. Note: S3 doesn't support traditional file flags, so this is a simplified implementation.

func (*FileSystem) ReadDir

func (fs *FileSystem) ReadDir(name string) ([]iosfs.DirEntry, error)

ReadDir reads the named directory and returns a list of directory entries sorted by filename.

func (*FileSystem) ReadFile

func (fs *FileSystem) ReadFile(name string) ([]byte, error)

ReadFile reads the named file and returns its contents.

func (*FileSystem) Remove

func (fs *FileSystem) Remove(name string) error

Remove removes a file or directory from S3. For directories, it removes the directory marker (key with trailing slash). Note: S3's DeleteObject succeeds even if the object doesn't exist.

func (*FileSystem) Rename

func (fs *FileSystem) Rename(oldpath, newpath string) error

Rename renames (moves) a file in S3 by copying and deleting.

func (*FileSystem) Stat

func (fs *FileSystem) Stat(name string) (os.FileInfo, error)

Stat returns file info for an S3 object.

func (*FileSystem) Sub

func (fs *FileSystem) Sub(dir string) (iosfs.FS, error)

Sub returns an fs.FS corresponding to the subtree rooted at dir.

func (*FileSystem) Truncate

func (fs *FileSystem) Truncate(name string, size int64) error

Truncate truncates a file to the specified size. For S3, this requires reading the file, truncating the data, and writing it back.

type MockS3Client

type MockS3Client struct {

	// Error injection for testing failure scenarios
	GetObjectErr    error
	PutObjectErr    error
	DeleteObjectErr error
	CopyObjectErr   error
	HeadObjectErr   error
	ListObjectsErr  error

	// Call tracking for assertions
	GetObjectCalls    []string
	PutObjectCalls    []string
	DeleteObjectCalls []string
	CopyObjectCalls   []copyObjectCall
	HeadObjectCalls   []string
	ListObjectsCalls  []string
	// contains filtered or unexported fields
}

MockS3Client is an in-memory mock implementation of S3Client for testing.

func NewMockS3Client

func NewMockS3Client() *MockS3Client

NewMockS3Client creates a new mock S3 client for testing.

func (*MockS3Client) CopyObject

func (m *MockS3Client) CopyObject(ctx context.Context, params *s3.CopyObjectInput, optFns ...func(*s3.Options)) (*s3.CopyObjectOutput, error)

CopyObject implements S3Client.

func (*MockS3Client) DeleteObject

func (m *MockS3Client) DeleteObject(ctx context.Context, params *s3.DeleteObjectInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)

DeleteObject implements S3Client.

func (*MockS3Client) GetObject

func (m *MockS3Client) GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)

GetObject implements S3Client.

func (*MockS3Client) GetTestObject

func (m *MockS3Client) GetTestObject(key string) ([]byte, bool)

GetTestObject retrieves a test object from the mock store.

func (*MockS3Client) HasObject

func (m *MockS3Client) HasObject(key string) bool

HasObject checks if an object exists in the mock store.

func (*MockS3Client) HeadObject

func (m *MockS3Client) HeadObject(ctx context.Context, params *s3.HeadObjectInput, optFns ...func(*s3.Options)) (*s3.HeadObjectOutput, error)

HeadObject implements S3Client.

func (*MockS3Client) ListObjectsV2

func (m *MockS3Client) ListObjectsV2(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error)

ListObjectsV2 implements S3Client.

func (*MockS3Client) ObjectCount

func (m *MockS3Client) ObjectCount() int

ObjectCount returns the number of objects in the mock store.

func (*MockS3Client) PutObject

func (m *MockS3Client) PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)

PutObject implements S3Client.

func (*MockS3Client) PutTestObject

func (m *MockS3Client) PutTestObject(key string, data []byte)

PutTestObject adds a test object directly to the mock store.

func (*MockS3Client) Reset

func (m *MockS3Client) Reset()

Reset clears all objects and error injections.

type S3Client

type S3Client interface {
	GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
	PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
	DeleteObject(ctx context.Context, params *s3.DeleteObjectInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)
	CopyObject(ctx context.Context, params *s3.CopyObjectInput, optFns ...func(*s3.Options)) (*s3.CopyObjectOutput, error)
	HeadObject(ctx context.Context, params *s3.HeadObjectInput, optFns ...func(*s3.Options)) (*s3.HeadObjectOutput, error)
	ListObjectsV2(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error)
}

S3Client defines the interface for S3 operations used by FileSystem. This interface allows for dependency injection and mock testing.

Jump to

Keyboard shortcuts

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