go_storage

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 43 Imported by: 0

README

Go Storage

A streaming storage abstraction for Go backup tools.

Supported backends:

  • Local filesystem
  • S3 and S3-compatible services (MinIO, Ceph, Wasabi, ...) via aws-sdk-go-v2
  • Azure Blob Storage (and Azurite)
  • Google Cloud Storage
  • SFTP
  • FTP / explicit FTPS
go get github.com/jkaninda/go-storage

Streaming API

Every backend implements the same Storage interface:

type Storage interface {
	Upload(ctx context.Context, localPath, remotePath string) error
	Download(ctx context.Context, remotePath, localPath string) error
	List(ctx context.Context, prefix string) ([]Item, error) // recursive
	Remove(ctx context.Context, remotePath string) error     // missing -> ErrNotFound
	Close() error

	Put(ctx context.Context, key string, r io.Reader, opts *PutOptions) (Item, error)
	Get(ctx context.Context, key string) (io.ReadCloser, Item, error)
	Stat(ctx context.Context, key string) (Item, error)
	PutIf(ctx context.Context, key string, r io.Reader, cond Condition, opts *PutOptions) (Item, error)
	ListDir(ctx context.Context, dir string) ([]Item, error) // non-recursive, files only
}
  • Put streams a reader of unknown length with bounded memory (no temp files, no whole-file buffering). If the reader fails or the context is cancelled, Put returns an error and no object (and no partial object) is left at the key: S3 aborts the multipart upload, Azure never commits the block list, GCS cancels the resumable upload, and SFTP/FTP/local write to <key>.<random>.partial and rename on success.
  • Get returns a streaming body; always Close it. On FTP the body holds the single control connection, so close it before making another call.
  • PutIf is a conditional write for small files such as a backup index (optimistic concurrency): Condition{IfNoneMatch: true} creates only if the key does not exist, Condition{IfMatch: item.ETag} replaces only if the object is unchanged. It returns ErrPreconditionFailed when the condition does not hold and ErrConditionNotSupported when the backend cannot evaluate it (fall back to locking).
  • Errors wrap the sentinels ErrNotFound, ErrPreconditionFailed and ErrConditionNotSupported; test them with errors.Is.
  • Keys are relative to the backend base (bucket, container, remote directory or local base path), use / separators and may not escape the base (..).
Backend Item.ETag PutIf IfNoneMatch PutIf IfMatch
S3 S3 ETag yes yes
Azure blob ETag yes yes
GCS object generation yes yes
Local <mtime-ns hex>-<size hex> yes (lock file) yes (lock file)
SFTP empty yes (O_EXCL) not supported
FTP empty not supported not supported

S3 PutIf uses a single PutObject request and is limited to 16 MiB.

Example: dump, compress and upload without temp files
package main

import (
	"compress/gzip"
	"context"
	"errors"
	"io"
	"log"
	"os/exec"
	"strings"

	storage "github.com/jkaninda/go-storage"
)

func main() {
	ctx := context.Background()
	s, err := storage.NewStorage(storage.StorageTypeS3, storage.Config{
		S3Bucket:    "backups",
		S3Region:    "us-east-1",
		S3KeyID:     "...",
		S3Secret:    "...",
		S3Endpoint:  "https://minio.example.com", // optional, for S3-compatible services
		S3ForcePath: true,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer s.Close()

	pr, pw := io.Pipe()
	go func() {
		gz := gzip.NewWriter(pw)
		cmd := exec.CommandContext(ctx, "pg_dump", "mydb")
		cmd.Stdout = gz
		err := cmd.Run()
		if err == nil {
			err = gz.Close()
		}
		pw.CloseWithError(err) // a non-nil error aborts the upload
	}()

	item, err := s.Put(ctx, "db/mydb-2026-01-01.sql.gz", pr, &storage.PutOptions{ContentType: "application/gzip"})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("uploaded %s (%d bytes, etag %s)", item.Key, item.Size, item.ETag)

	// Restore: stream it back.
	body, _, err := s.Get(ctx, item.Key)
	if errors.Is(err, storage.ErrNotFound) {
		log.Fatal("backup not found")
	} else if err != nil {
		log.Fatal(err)
	}
	defer body.Close()
	zr, _ := gzip.NewReader(body)
	_, _ = io.Copy(io.Discard, zr)

	// Update an index file with optimistic concurrency.
	idx, err := s.Stat(ctx, "db/index.json")
	cond := storage.Condition{IfMatch: idx.ETag}
	if errors.Is(err, storage.ErrNotFound) {
		cond = storage.Condition{IfNoneMatch: true}
	}
	_, err = s.PutIf(ctx, "db/index.json", strings.NewReader(`{"backups":[]}`), cond, nil)
	if errors.Is(err, storage.ErrPreconditionFailed) {
		// someone else updated the index: re-read, merge and retry
	}
}

Configuration

storage.NewStorage(storageType, storage.Config{...}) with storageType one of s3, gcs, azure, sftp, ftp, local.

Field Backend Description
LocalPath local Base directory (default /backup)
S3Bucket s3 Bucket (required)
S3Region s3 Region (default from AWS config, else us-east-1)
S3KeyID, S3Secret, S3SessionToken s3 Static credentials; when empty the default AWS chain is used (env, shared profile, IRSA/web identity, ECS/EC2 roles)
S3Profile s3 Shared config profile
S3Endpoint s3 Custom endpoint (MinIO etc.); without a scheme https:// is assumed (http:// with S3DisableTLS)
S3ForcePath s3 Path-style addressing
S3DisableTLS s3 Use http:// for scheme-less endpoints
S3StorageClass s3 e.g. STANDARD_IA, GLACIER_IR
S3SSE, S3SSEKMSKeyID s3 Server-side encryption: AES256 or aws:kms (+ key id)
S3PartSize s3 Multipart part size (default 64 MiB, min 5 MiB)
S3Concurrency s3 Parallel part uploads (default 2); memory ≈ part size × concurrency
AzureAccount, AzureKey azure Shared key credentials
AzureSASToken azure SAS token (used instead of the shared key when set)
AzureContainer azure Container (required)
AzureEndpoint azure Domain suffix (default blob.core.windows.net) or a full service URL such as http://127.0.0.1:10000/devstoreaccount1 (Azurite)
GCSBucket gcs Bucket (required)
GCSCredentialsFile, GCSCredentialsJSON gcs Credentials; default is Application Default Credentials
GCSEndpoint gcs Custom endpoint
SFTPHost, SFTPPort sftp Server (port default 22)
SFTPUsername, SFTPPassword sftp Password authentication
SFTPIdentityFile, SFTPIdentityPassphrase sftp Private key authentication (an SSH agent is used too when available)
SFTPKnownHostsFile sftp known_hosts file (default ~/.ssh/known_hosts); host keys are always verified unless...
SFTPIgnoreKnownHosts sftp ...this is true (insecure)
SFTPDirectory sftp Remote base directory (default: login directory)
FTPHost, FTPPort, FTPUsername, FTPPassword ftp Server and credentials (port default 21)
FTPDirectory ftp Remote base directory (default: login directory)
FTPTLS ftp Explicit FTPS (AUTH TLS)

The library never reads environment variables itself (except what the cloud SDKs do for their default credential chains, and SSH_AUTH_SOCK for the SSH agent).

Testing

go test ./...                       # unit tests: local + in-process SFTP server
go test -tags integration ./...     # + MinIO, Azurite, fake-gcs-server, FTP via docker

Integration tests skip when docker is unavailable. Images can be overridden with GO_STORAGE_MINIO_IMAGE, GO_STORAGE_AZURITE_IMAGE, GO_STORAGE_FAKEGCS_IMAGE and GO_STORAGE_FTP_IMAGE.

Deprecated: pkg/ (v0.1 API)

The packages under pkg/ (pkg/local, pkg/s3, pkg/ssh, pkg/ftp, pkg/azure) are the legacy v0.1 API. They still compile but are deprecated and will be removed in a future release; use the root package instead.

License

MIT License, Copyright (c) 2024 Jonas Kaninda. See LICENSE.

Documentation

Overview

Package go_storage provides a uniform, streaming storage abstraction over S3 (and S3-compatible services), Azure Blob Storage, Google Cloud Storage, SFTP, FTP and the local filesystem.

All backends implement Storage. Objects are addressed by keys that are relative to the backend base (bucket, container, remote directory or local base path) and always use forward slashes.

Index

Constants

View Source
const (
	DefaultS3PartSize    int64 = 64 << 20
	MinS3PartSize        int64 = 5 << 20
	DefaultS3Concurrency       = 2
	DefaultS3Region            = "us-east-1"
)

S3 defaults.

View Source
const DefaultLocalPath = "/backup"

DefaultLocalPath is the base directory of the local backend when Config.LocalPath is empty.

Variables

View Source
var (
	// ErrNotFound is returned (wrapped) by Stat, Get and Remove when the key does not exist.
	ErrNotFound = errors.New("storage: object not found")
	// ErrPreconditionFailed is returned (wrapped) by PutIf when the condition does not hold.
	ErrPreconditionFailed = errors.New("storage: precondition failed")
	// ErrConditionNotSupported is returned (wrapped) by PutIf when the backend cannot
	// evaluate the requested condition atomically. Callers should fall back to locking.
	ErrConditionNotSupported = errors.New("storage: conditional write not supported by backend")
)

Sentinel errors. Backends wrap them with %w, so test with errors.Is.

Functions

This section is empty.

Types

type AzureStorage

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

AzureStorage implements Storage interface for Azure Blob Storage.

func NewAzureStorage

func NewAzureStorage(config Config) (*AzureStorage, error)

NewAzureStorage creates a new Azure Blob Storage instance.

Authentication: AzureSASToken if set, otherwise shared key (AzureAccount/AzureKey), otherwise anonymous.

func (*AzureStorage) Client

func (a *AzureStorage) Client() *azblob.Client

Client returns the underlying azblob client.

func (*AzureStorage) Close

func (a *AzureStorage) Close() error

Close releases resources (no-op).

func (*AzureStorage) Download

func (a *AzureStorage) Download(ctx context.Context, remotePath string, localPath string) error

Download downloads a file from Azure Blob Storage.

func (*AzureStorage) Get

func (a *AzureStorage) Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

Get streams the blob body.

func (*AzureStorage) List

func (a *AzureStorage) List(ctx context.Context, prefix string) ([]Item, error)

List lists blobs (recursively) with the given prefix.

func (*AzureStorage) ListDir

func (a *AzureStorage) ListDir(ctx context.Context, dir string) ([]Item, error)

ListDir lists the blobs directly under dir.

func (*AzureStorage) Put

func (a *AzureStorage) Put(ctx context.Context, key string, r io.Reader, opts *PutOptions) (Item, error)

Put streams r to key with a block upload; the block list is only committed when the whole stream was read successfully.

func (*AzureStorage) PutIf

func (a *AzureStorage) PutIf(ctx context.Context, key string, r io.Reader, cond Condition, opts *PutOptions) (Item, error)

PutIf writes r to key with If-Match / If-None-Match: * access conditions.

func (*AzureStorage) Remove

func (a *AzureStorage) Remove(ctx context.Context, remotePath string) error

Remove deletes a blob.

func (*AzureStorage) Stat

func (a *AzureStorage) Stat(ctx context.Context, key string) (Item, error)

Stat returns blob properties.

func (*AzureStorage) Upload

func (a *AzureStorage) Upload(ctx context.Context, localPath string, remotePath string) error

Upload uploads a file to Azure Blob Storage.

type Condition

type Condition struct {
	IfMatch     string // only write if the current ETag equals this
	IfNoneMatch bool   // only write if the object does not exist
}

Condition is a precondition for PutIf. Exactly one field must be set; a zero Condition is rejected (it would otherwise silently become an unconditional write, e.g. when an empty ETag is passed as IfMatch).

type Config

type Config struct {
	// Local configuration
	LocalPath string // base directory for the local backend (default "/backup")

	// S3 configuration
	S3Region       string
	S3Bucket       string
	S3Profile      string
	S3KeyID        string
	S3Secret       string
	S3SessionToken string
	S3Endpoint     string
	S3ForcePath    bool
	S3DisableTLS   bool
	S3StorageClass string // e.g. STANDARD, STANDARD_IA, GLACIER_IR
	S3SSE          string // "AES256" or "aws:kms"
	S3SSEKMSKeyID  string // KMS key id when S3SSE is "aws:kms"
	S3PartSize     int64  // multipart part size in bytes (default 64 MiB, min 5 MiB)
	S3Concurrency  int    // multipart upload concurrency (default 2)

	// B2 configuration (reserved, no backend implementation yet)
	B2KeyID                 string
	B2AppKey                string
	B2Bucket                string
	B2ConcurrentConnections int
	B2ForcePath             bool

	// Google Cloud Storage configuration
	GCSBucket          string
	GCSEndpoint        string
	GCSCredentialsFile string
	GCSCredentialsJSON string

	// Azure configuration
	AzureAccount   string
	AzureKey       string
	AzureContainer string
	// AzureEndpoint is either a domain suffix (default "blob.core.windows.net",
	// the service URL becomes https://<account>.<endpoint>) or a full service
	// URL containing a scheme (e.g. "http://127.0.0.1:10000/devstoreaccount1"
	// for Azurite), used as is.
	AzureEndpoint string
	// AzureSASToken, when set, is used instead of the shared key.
	AzureSASToken string

	// SFTP configuration
	SFTPHost               string
	SFTPPort               string
	SFTPUsername           string
	SFTPPassword           string
	SFTPDirectory          string
	SFTPIdentityFile       string
	SFTPIdentityPassphrase string
	SFTPKnownHostsFile     string
	SFTPIgnoreKnownHosts   bool

	// FTP configuration
	FTPHost      string
	FTPPort      string
	FTPUsername  string
	FTPPassword  string
	FTPDirectory string
	FTPTLS       bool // explicit FTPS (AUTH TLS)
}

Config holds configuration options for creating storage instances.

type FTPStorage

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

FTPStorage implements Storage interface for FTP (optionally explicit FTPS).

FTP uses a single control connection, so all operations are serialised by a mutex. The body returned by Get holds that connection until it is closed: a Get body MUST be closed before any other call on the same FTPStorage, otherwise that call blocks.

func NewFTPStorage

func NewFTPStorage(config Config) (*FTPStorage, error)

NewFTPStorage creates a new FTP storage instance.

func (*FTPStorage) Close

func (f *FTPStorage) Close() error

Close releases resources.

func (*FTPStorage) Download

func (f *FTPStorage) Download(ctx context.Context, remotePath string, localPath string) error

Download downloads a file via FTP.

func (*FTPStorage) Get

func (f *FTPStorage) Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

Get opens key for streaming reads. The returned body holds the FTP control connection: close it before issuing any other call on this storage.

func (*FTPStorage) List

func (f *FTPStorage) List(ctx context.Context, prefix string) ([]Item, error)

List lists files and directories (recursively) whose key starts with prefix.

func (*FTPStorage) ListDir

func (f *FTPStorage) ListDir(ctx context.Context, dir string) ([]Item, error)

ListDir lists the files directly inside dir.

func (*FTPStorage) Put

func (f *FTPStorage) Put(ctx context.Context, key string, r io.Reader, _ *PutOptions) (Item, error)

Put streams r to <key>.<rand>.partial and renames it on success.

func (*FTPStorage) PutIf

func (f *FTPStorage) PutIf(_ context.Context, key string, _ io.Reader, _ Condition, _ *PutOptions) (Item, error)

PutIf is not supported on FTP: it always returns ErrConditionNotSupported. Callers should fall back to a lock-based protocol.

func (*FTPStorage) Remove

func (f *FTPStorage) Remove(ctx context.Context, remotePath string) error

Remove deletes a file via FTP.

func (*FTPStorage) Stat

func (f *FTPStorage) Stat(ctx context.Context, key string) (Item, error)

Stat returns metadata for key (from a listing of its parent directory).

func (*FTPStorage) Upload

func (f *FTPStorage) Upload(ctx context.Context, localPath string, remotePath string) error

Upload uploads a file via FTP.

type GCSStorage

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

GCSStorage implements Storage interface for Google Cloud Storage.

func NewGCSStorage

func NewGCSStorage(config Config) (*GCSStorage, error)

NewGCSStorage creates a new Google Cloud Storage instance.

Credentials: GCSCredentialsJSON, else GCSCredentialsFile, else Application Default Credentials. The STORAGE_EMULATOR_HOST environment variable is honoured by the Google client library itself.

func (*GCSStorage) Client

func (g *GCSStorage) Client() *storage.Client

Client returns the underlying GCS client.

func (*GCSStorage) Close

func (g *GCSStorage) Close() error

Close releases resources.

func (*GCSStorage) Download

func (g *GCSStorage) Download(ctx context.Context, remotePath string, localPath string) error

Download downloads a file from GCS.

func (*GCSStorage) Get

func (g *GCSStorage) Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

Get streams the object body.

func (*GCSStorage) List

func (g *GCSStorage) List(ctx context.Context, prefix string) ([]Item, error)

List lists objects (recursively) with the given prefix.

func (*GCSStorage) ListDir

func (g *GCSStorage) ListDir(ctx context.Context, dir string) ([]Item, error)

ListDir lists the objects directly under dir.

func (*GCSStorage) Put

func (g *GCSStorage) Put(ctx context.Context, key string, r io.Reader, opts *PutOptions) (Item, error)

Put streams r to key.

func (*GCSStorage) PutIf

func (g *GCSStorage) PutIf(ctx context.Context, key string, r io.Reader, cond Condition, opts *PutOptions) (Item, error)

PutIf writes r to key with a generation precondition (IfMatch is the generation as returned in Item.ETag).

func (*GCSStorage) Remove

func (g *GCSStorage) Remove(ctx context.Context, remotePath string) error

Remove deletes an object.

func (*GCSStorage) Stat

func (g *GCSStorage) Stat(ctx context.Context, key string) (Item, error)

Stat returns object attributes.

func (*GCSStorage) Upload

func (g *GCSStorage) Upload(ctx context.Context, localPath string, remotePath string) error

Upload uploads a file to GCS.

type Item

type Item struct {
	Key          string    // The path/key of the item, relative to the backend base
	ModifiedTime time.Time // Last modification time
	Size         int64     // Size in bytes (0 for directories)
	IsDirectory  bool      // Whether this item is a directory
	// ETag is an opaque version token usable with Condition.IfMatch
	// (S3/Azure ETag; GCS generation as decimal string; local:
	// "<mtime-unixnano hex>-<size hex>"; SFTP/FTP: "").
	ETag string
	// VersionID is the S3 version id when bucket versioning is enabled.
	VersionID string
}

Item represents a file or directory in remote storage.

type LocalStorage

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

LocalStorage implements the Storage interface using the local filesystem. It is safe for concurrent use.

func NewLocalStorage

func NewLocalStorage(basePath string) (*LocalStorage, error)

NewLocalStorage creates a new LocalStorage instance with the given base directory. The base directory will be created if it doesn't exist.

func (*LocalStorage) BasePath

func (s *LocalStorage) BasePath() string

BasePath returns the base directory path of the storage.

func (*LocalStorage) Close

func (s *LocalStorage) Close() error

Close releases any resources held by the storage implementation (no-op).

func (*LocalStorage) Download

func (s *LocalStorage) Download(ctx context.Context, remotePath string, localPath string) error

Download downloads a file from storage to a local path.

func (*LocalStorage) Get

func (s *LocalStorage) Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

Get opens key for reading.

func (*LocalStorage) List

func (s *LocalStorage) List(ctx context.Context, prefix string) ([]Item, error)

List returns all items (files and directories, recursively) whose key starts with prefix.

func (*LocalStorage) ListDir

func (s *LocalStorage) ListDir(ctx context.Context, dir string) ([]Item, error)

ListDir lists the files directly inside dir.

func (*LocalStorage) Put

func (s *LocalStorage) Put(ctx context.Context, key string, r io.Reader, _ *PutOptions) (Item, error)

Put streams r to key via a temporary file that is renamed on success.

func (*LocalStorage) PutIf

func (s *LocalStorage) PutIf(ctx context.Context, key string, r io.Reader, cond Condition, _ *PutOptions) (Item, error)

PutIf writes r to key only if cond holds. It uses an exclusive lock file (<key>.lock) so it is atomic with respect to other PutIf/Put calls on the same filesystem.

func (*LocalStorage) Remove

func (s *LocalStorage) Remove(ctx context.Context, remotePath string) error

Remove deletes a file (or directory tree) from storage.

func (*LocalStorage) Stat

func (s *LocalStorage) Stat(ctx context.Context, key string) (Item, error)

Stat returns metadata for key.

func (*LocalStorage) Upload

func (s *LocalStorage) Upload(ctx context.Context, localPath string, remotePath string) error

Upload uploads a local file to the storage with the given target name.

type PutOptions

type PutOptions struct {
	ContentType string
	Metadata    map[string]string
	Size        int64 // optional size hint; -1 or 0 = unknown
}

PutOptions are optional parameters for Put and PutIf.

type S3Storage

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

S3Storage implements Storage for Amazon S3 and S3-compatible services (MinIO, Ceph, Wasabi, ...).

func NewS3Storage

func NewS3Storage(config Config) (*S3Storage, error)

NewS3Storage creates a new S3 storage instance.

Credentials: static keys (S3KeyID/S3Secret/S3SessionToken) when set, otherwise the default AWS credential chain (environment, shared profile S3Profile, web identity/IRSA, ECS/EC2 roles).

func (*S3Storage) Client

func (s *S3Storage) Client() *s3.Client

Client returns the underlying S3 client.

func (*S3Storage) Close

func (s *S3Storage) Close() error

Close releases resources (no-op).

func (*S3Storage) Download

func (s *S3Storage) Download(ctx context.Context, remotePath string, localPath string) error

Download downloads a file from S3.

func (*S3Storage) Get

func (s *S3Storage) Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

Get streams the object body.

func (*S3Storage) List

func (s *S3Storage) List(ctx context.Context, prefix string) ([]Item, error)

List lists objects (recursively) with the given prefix.

func (*S3Storage) ListDir

func (s *S3Storage) ListDir(ctx context.Context, dir string) ([]Item, error)

ListDir lists the objects directly under dir.

func (*S3Storage) Put

func (s *S3Storage) Put(ctx context.Context, key string, r io.Reader, opts *PutOptions) (Item, error)

Put streams r to key using a multipart upload (aborted on error).

func (*S3Storage) PutIf

func (s *S3Storage) PutIf(ctx context.Context, key string, r io.Reader, cond Condition, opts *PutOptions) (Item, error)

PutIf performs a conditional single-request PutObject (If-Match / If-None-Match: *). The body is buffered and limited to 16 MiB.

func (*S3Storage) Remove

func (s *S3Storage) Remove(ctx context.Context, remotePath string) error

Remove deletes an object. A missing key returns ErrNotFound (checked with HeadObject because DeleteObject is idempotent on S3).

func (*S3Storage) Stat

func (s *S3Storage) Stat(ctx context.Context, key string) (Item, error)

Stat returns object metadata (HeadObject).

func (*S3Storage) Upload

func (s *S3Storage) Upload(ctx context.Context, localPath string, remotePath string) error

Upload uploads a file to S3.

type SFTPStorage

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

SFTPStorage implements Storage interface for SFTP.

func NewSFTPStorage

func NewSFTPStorage(config Config) (*SFTPStorage, error)

NewSFTPStorage creates a new SFTP storage instance.

Host keys are verified against SFTPKnownHostsFile (or ~/.ssh/known_hosts and /etc/ssh/ssh_known_hosts) unless SFTPIgnoreKnownHosts is true.

func (*SFTPStorage) Client

func (s *SFTPStorage) Client() *sftp.Client

Client returns the underlying sftp client.

func (*SFTPStorage) Close

func (s *SFTPStorage) Close() error

Close releases resources.

func (*SFTPStorage) Download

func (s *SFTPStorage) Download(ctx context.Context, remotePath string, localPath string) error

Download downloads a file via SFTP.

func (*SFTPStorage) Get

func (s *SFTPStorage) Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

Get opens key for streaming reads.

func (*SFTPStorage) List

func (s *SFTPStorage) List(ctx context.Context, prefix string) ([]Item, error)

List lists files and directories (recursively) whose key starts with prefix.

func (*SFTPStorage) ListDir

func (s *SFTPStorage) ListDir(ctx context.Context, dir string) ([]Item, error)

ListDir lists the files directly inside dir.

func (*SFTPStorage) Put

func (s *SFTPStorage) Put(ctx context.Context, key string, r io.Reader, _ *PutOptions) (Item, error)

Put streams r to <key>.<rand>.partial and renames it to key on success.

func (*SFTPStorage) PutIf

func (s *SFTPStorage) PutIf(ctx context.Context, key string, r io.Reader, cond Condition, _ *PutOptions) (Item, error)

PutIf supports only Condition.IfNoneMatch (via O_EXCL on the final path). IfMatch returns ErrConditionNotSupported.

func (*SFTPStorage) Remove

func (s *SFTPStorage) Remove(ctx context.Context, remotePath string) error

Remove deletes a file via SFTP.

func (*SFTPStorage) Stat

func (s *SFTPStorage) Stat(ctx context.Context, key string) (Item, error)

Stat returns metadata for key.

func (*SFTPStorage) Upload

func (s *SFTPStorage) Upload(ctx context.Context, localPath string, remotePath string) error

Upload uploads a file via SFTP.

type Storage

type Storage interface {
	// Upload uploads a local file to the remote storage with the given target name.
	Upload(ctx context.Context, localPath string, remotePath string) error

	// Download downloads a file from remote storage to a local path.
	Download(ctx context.Context, remotePath string, localPath string) error

	// List returns all items (recursively) in the storage that match the given prefix.
	List(ctx context.Context, prefix string) ([]Item, error)

	// Remove deletes a file from remote storage. A missing key returns an
	// error wrapping ErrNotFound.
	Remove(ctx context.Context, remotePath string) error

	// Close releases any resources held by the storage implementation.
	Close() error

	// Put streams r to key. r may be of unknown length; memory use is bounded.
	// If reading r fails or ctx is cancelled, Put returns an error and no
	// (partial) object is left at key.
	Put(ctx context.Context, key string, r io.Reader, opts *PutOptions) (Item, error)

	// Get opens key for streaming reads. The caller must Close the body.
	// A missing key returns an error wrapping ErrNotFound.
	Get(ctx context.Context, key string) (io.ReadCloser, Item, error)

	// Stat returns metadata for key. A missing key returns an error wrapping ErrNotFound.
	Stat(ctx context.Context, key string) (Item, error)

	// PutIf writes r to key only if cond holds, atomically with respect to
	// other PutIf calls. It returns an error wrapping ErrPreconditionFailed when
	// the condition does not hold, or ErrConditionNotSupported when the backend
	// cannot evaluate it. Intended for small objects (index files).
	PutIf(ctx context.Context, key string, r io.Reader, cond Condition, opts *PutOptions) (Item, error)

	// ListDir lists only the files directly inside dir (dir is treated as a
	// directory: "a/b" never matches "a/bc/x"; "" = root). Non-recursive, no
	// directories are returned. A missing directory yields an empty list.
	ListDir(ctx context.Context, dir string) ([]Item, error)
}

Storage defines the interface for remote file storage operations. All implementations are safe for concurrent use (see FTPStorage for the one restriction regarding open Get bodies).

func NewStorage

func NewStorage(storageType StorageType, config Config) (Storage, error)

NewStorage creates a new Storage instance based on the specified type and configuration.

type StorageType

type StorageType string

StorageType represents the type of storage backend.

const (
	StorageTypeS3    StorageType = "s3"
	StorageTypeGCS   StorageType = "gcs"
	StorageTypeAzure StorageType = "azure"
	StorageTypeSFTP  StorageType = "sftp"
	StorageTypeFTP   StorageType = "ftp"
	StorageTypeLocal StorageType = "local"
)

Supported storage types.

Directories

Path Synopsis
pkg
Package pkg is the legacy v0.1 API of go-storage.
Package pkg is the legacy v0.1 API of go-storage.
azure
Package azure is the legacy v0.1 API of go-storage.
Package azure is the legacy v0.1 API of go-storage.
ftp
Package ftp is the legacy v0.1 API of go-storage.
Package ftp is the legacy v0.1 API of go-storage.
local
Package local is the legacy v0.1 API of go-storage.
Package local is the legacy v0.1 API of go-storage.
s3
Package s3 is the legacy v0.1 API of go-storage.
Package s3 is the legacy v0.1 API of go-storage.
ssh
Package ssh is the legacy v0.1 API of go-storage.
Package ssh is the legacy v0.1 API of go-storage.

Jump to

Keyboard shortcuts

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