simplestorage

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Example (BucketManagementWorkflow)
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create a new bucket
	info, err := client.CreateBucket(ctx, "my-new-bucket",
		simplestorage.WithEnableSnapshot(),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	// Create a snapshot
	snapshot, err := client.Snapshot(ctx, "my-new-bucket", "Initial state")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	// Fork from the snapshot
	forkInfo, err := client.ForkBucket(ctx, "my-new-bucket", "my-forked-bucket",
		simplestorage.WithSnapshotVersion(snapshot.Version),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
	_ = forkInfo // Use the fork info

	// Get bucket info
	info, err = client.Info(ctx, "my-forked-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Forked bucket info: %+v\n", info)

	// Clean up - delete both buckets
	// Note: Buckets must be empty before they can be deleted
	err = client.DeleteBucket(ctx, "my-forked-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	err = client.DeleteBucket(ctx, "my-new-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrBucketNameRequired is returned when a bucket name is required but not provided.
	ErrBucketNameRequired = errors.New("simplestorage: bucket name required for bucket management operations")

	// ErrBucketNotFound is returned when a bucket operation fails because the bucket doesn't exist.
	ErrBucketNotFound = errors.New("simplestorage: bucket not found")

	// ErrBucketNotEmpty is returned when trying to delete a non-empty bucket.
	ErrBucketNotEmpty = errors.New("simplestorage: bucket not empty")

	// ErrSnapshotRequired is returned when a snapshot version is required but not provided.
	ErrSnapshotRequired = errors.New("simplestorage: snapshot version required for this operation")
)
View Source
var ErrNoBucketName = errors.New("bucket name not set: provide the TIGRIS_STORAGE_BUCKET environment variable or use WithBucket option")

ErrNoBucketName is returned when no bucket name is provided via the TIGRIS_STORAGE_BUCKET environment variable or the WithBucket option.

Functions

This section is empty.

Types

type AccessType added in v0.7.0

type AccessType string

AccessType controls whether an object or bucket is publicly readable.

const (
	// AccessPrivate restricts access to authenticated callers (S3 canned ACL "private").
	AccessPrivate AccessType = "private"
	// AccessPublic makes the object or bucket world-readable (S3 canned ACL "public-read").
	AccessPublic AccessType = "public"
)

type BucketInfo

type BucketInfo struct {
	Name    string    // Bucket name
	Created time.Time // Creation time

	// Tigris-specific fields
	SnapshotsEnabled bool   // True if snapshots are enabled
	IsForkParent     bool   // True if this bucket has forks
	SourceBucket     string // If this is a fork, the source bucket
	SourceSnapshot   string // If this is a fork, the snapshot version
}

BucketInfo contains metadata about a bucket.

type BucketOption

type BucketOption func(*BucketOptions)

BucketOption is a functional option for bucket management operations.

func WithBucketAccess added in v0.7.0

func WithBucketAccess(access AccessType) BucketOption

WithBucketAccess sets the bucket-level canned ACL (public or private). Use AccessPublic to allow anonymous reads via public-read, or AccessPrivate (the default) to require authenticated access.

Example
package main

import (
	"context"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Public-read bucket: objects inside are world-readable unless overridden.
	info, err := client.CreateBucket(ctx, "public-assets",
		simplestorage.WithBucketAccess(simplestorage.AccessPublic),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
	_ = info
}

func WithBucketRegion

func WithBucketRegion(region string) BucketOption

WithBucketRegion sets static replication region for the bucket.

For more information, see the Tigris documentation1.

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create a bucket with static replication to specific regions
	info, err := client.CreateBucket(ctx, "my-multi-region-bucket",
		simplestorage.WithBucketRegion("fra"), // Frankfurt, Germany
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Created bucket: %s\n", info.Name)
}

func WithConsistentRead added in v0.7.0

func WithConsistentRead() BucketOption

WithConsistentRead enables consistent read mode for the bucket.

func WithDefaultTier added in v0.7.0

func WithDefaultTier(tier string) BucketOption

WithDefaultTier sets the storage class tier for the bucket. Valid values: "STANDARD", "STANDARD_IA", "GLACIER", "GLACIER_IR"

Example
package main

import (
	"context"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Archive-tier bucket for cold storage.
	info, err := client.CreateBucket(ctx, "cold-archive",
		simplestorage.WithDefaultTier("GLACIER"),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
	_ = info
}

func WithEnableSnapshot

func WithEnableSnapshot() BucketOption

WithEnableSnapshot enables snapshot capability when creating a bucket.

func WithForkSourceSnapshot added in v0.7.0

func WithForkSourceSnapshot(snapshot string) BucketOption

WithForkSourceSnapshot specifies the snapshot version when forking from a bucket. Use this with CreateBucket when forking from a specific snapshot version.

func WithGrabForkInfo added in v0.7.0

func WithGrabForkInfo() BucketOption

WithGrabForkInfo instructs the Buckets() call to grab additional information about bucket forkability and the snapshot each bucket was based on.

Using this will incur an additional Tigris round trip per invocation.

func WithListLimit

func WithListLimit(limit int32) BucketOption

WithListLimit sets the maximum number of buckets to return in ListBuckets.

func WithListToken

func WithListToken(token string) BucketOption

WithListToken sets the continuation token for paginated ListBuckets calls.

func WithSnapshotVersion

func WithSnapshotVersion(version string) BucketOption

WithSnapshotVersion specifies a snapshot version to target. Use this when forking from a specific snapshot version.

type BucketOptions

type BucketOptions struct {
	// EnableSnapshot enables snapshot capability on bucket creation.
	EnableSnapshot bool

	// SnapshotVersion specifies a snapshot version to target (for forking from specific snapshot).
	SnapshotVersion string

	// SourceBucketSnapshot specifies the snapshot version to fork from.
	SourceBucketSnapshot string

	// Region sets static replication region for the bucket.
	// This field is stored for visibility but the actual behavior is configured
	// via S3Options (see WithBucketRegion). Keeping the field enables debugging
	// and potential future use in bucket info responses.
	Region string

	// DefaultTier sets the storage class tier for the bucket.
	DefaultTier string

	// Consistency sets the consistency level for the bucket ("strict" or "default").
	Consistency string

	// Access sets the bucket-level access type (public or private).
	Access AccessType

	// MaxKeys sets the maximum number of results to return in ListBuckets.
	MaxKeys *int32

	// ContinuationToken is the pagination token for ListBuckets.
	ContinuationToken *string

	// S3Options are additional S3 options passed through to the underlying client.
	S3Options []func(*s3.Options)

	// GrabForkInfo makes Buckets calls grab additional information about buckets from
	// Tigris about forkability and what snapshot the bucket was forked from.
	GrabForkInfo bool
}

BucketOptions for bucket-level operations.

type Client

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

Client is a high-level client for Tigris that simplifies common interactions to very high level calls.

func New

func New(ctx context.Context, options ...Option) (*Client, error)

New creates a new Client based on the options provided and defaults loaded from the environment.

By default New reads the following environment variables for setting its defaults:

* `TIGRIS_STORAGE_BUCKET`: the name of the bucket for all Tigris operations. If this is not set in the environment or via the WithBucket, New() will return an error containing ErrNoBucketName. * `TIGRIS_STORAGE_ACCESS_KEY_ID`: The access key ID of the Tigris authentication keypair. If this is not set in the environment or via WithAccessKeypair, New() will load configuration via the AWS configuration resolution method. * `TIGRIS_STORAGE_SECRET_ACCESS_KEY`: The secret access key of the Tigris authentication keypair. If this is not set in the environment or via WithAccessKeypair, New() will load configuration via the AWS configuration resolution method.

The returned Client will default to having its operations performed on the specified bucket. If individual calls need to operate against arbitrary buckets, override it with OverrideBucket.

func (*Client) Buckets added in v0.7.0

func (c *Client) Buckets(ctx context.Context, opts ...BucketOption) iter.Seq2[*BucketInfo, error]

Buckets lists all buckets that the authenticated user has access to.

This returns an iterator over all of your buckets. If you want this to include Tigris-specific information such as forkability and what snapshot this bucket was based upon, use the WithGrabForkInfo() functional option.

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// ListBuckets returns an iterator that transparently handles pagination.
	for bucket, err := range client.Buckets(ctx) {
		if err != nil {
			log.Fatal(err) // handle the error here
		}

		fmt.Printf("Bucket: %s (created: %s)\n", bucket.Name, bucket.Created)
	}
}

func (*Client) CreateBucket

func (c *Client) CreateBucket(ctx context.Context, bucket string, opts ...BucketOption) (*BucketInfo, error)

CreateBucket creates a new bucket with the given name.

For Tigris-specific features like snapshots, use options like WithEnableSnapshot().

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	// Create a simplestorage client (requires TIGRIS_STORAGE_BUCKET env var or WithBucket option)
	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create a standard bucket
	info, err := client.CreateBucket(ctx, "my-new-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Created bucket: %s\n", info.Name)
}
Example (Snapshot)
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create a snapshot-enabled bucket (Tigris feature)
	info, err := client.CreateBucket(ctx, "my-snapshot-bucket",
		simplestorage.WithEnableSnapshot(),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Created bucket with snapshots: %s\n", info.Name)
}

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, key string, opts ...ClientOption) error

Delete removes an object from Tigris.

func (*Client) DeleteBucket

func (c *Client) DeleteBucket(ctx context.Context, bucket string, opts ...BucketOption) error

DeleteBucket deletes the bucket with the given name.

If the bucket is not empty, returns ErrBucketNotEmpty. The bucket must be manually emptied before deletion.

Example
package main

import (
	"context"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Delete a bucket (fails if not empty)
	err = client.DeleteBucket(ctx, "my-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}
}

func (*Client) For added in v0.5.0

func (c *Client) For(bucket string) *Client

For returns a copy of the Client with the bucket set as the default for all operations.

This is useful when you need to work with multiple buckets while reusing the same underlying connection and configuration.

func (*Client) ForkBucket

func (c *Client) ForkBucket(ctx context.Context, source, target string, opts ...BucketOption) (*BucketInfo, error)

ForkBucket creates a fork of the source bucket with the given target name.

Use WithSnapshotVersion() to fork from a specific snapshot version.

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Fork a bucket
	forkInfo, err := client.ForkBucket(ctx, "original-bucket", "forked-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Forked bucket: %s (from: %s)\n", forkInfo.Name, forkInfo.SourceBucket)

	// Fork from a specific snapshot version
	forkInfo, err = client.ForkBucket(ctx, "original-bucket", "forked-bucket-v2",
		simplestorage.WithSnapshotVersion("snapshot-version-id"),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Forked from snapshot: %s\n", forkInfo.SourceSnapshot)
}

func (*Client) Get

func (c *Client) Get(ctx context.Context, key string, opts ...ClientOption) (*Object, error)

Get fetches the contents of an object and its metadata from Tigris.

Example (ResponseOverrides)
package main

import (
	"context"
	"io"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Force the response Content-Disposition so browsers download rather than render.
	obj, err := client.Get(ctx, "reports/q1.pdf",
		simplestorage.WithResponseContentDisposition(`attachment; filename="q1.pdf"`),
		simplestorage.WithResponseContentType("application/pdf"),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
	defer obj.Body.Close()

	_, err = io.Copy(io.Discard, obj.Body)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
}

func (*Client) Head added in v0.4.0

func (c *Client) Head(ctx context.Context, key string, opts ...ClientOption) (*Object, error)

Head retrieves metadata for an object without downloading its content.

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	info, err := client.Head(ctx, "reports/q1.pdf")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("size=%d type=%s\n", info.Size, info.ContentType)
}
Example (SnapshotVersion)
package main

import (
	"context"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	info, err := client.Head(ctx, "reports/q1.pdf",
		simplestorage.WithQuerySnapshotVersion("2024-01-01T00:00:00Z"),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
	_ = info
}

func (*Client) Info added in v0.7.0

func (c *Client) Info(ctx context.Context, bucket string, opts ...BucketOption) (*BucketInfo, error)

Info retrieves metadata about the bucket with the given name.

This includes Tigris-specific information like whether snapshots are enabled and whether the bucket is a fork of another bucket.

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Get bucket information
	info, err := client.Info(ctx, "my-bucket")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Snapshots enabled: %v\n", info.SnapshotsEnabled)
	fmt.Printf("Is fork parent: %v\n", info.IsForkParent)
	fmt.Printf("Source bucket: %s\n", info.SourceBucket)
	fmt.Printf("Source snapshot: %s\n", info.SourceSnapshot)
}

func (*Client) List

func (c *Client) List(ctx context.Context, opts ...ListOption) iter.Seq2[*Object, error]

List returns a list of objects matching the given criteria.

This returns an iterator so you can loop over the values. The iterator handles pagination for you; the page size can be tuned with WithMaxKeys. Combine WithPrefix and WithDelimiter to walk a single "directory" level, or WithStartAfter and WithContinueToken to resume a previous listing.

Example (Delimiter)
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Walk one "directory" level under prefix "reports/" using "/" as a delimiter.
	for obj, err := range client.List(ctx, simplestorage.WithPrefix("reports/"), simplestorage.WithDelimiter("/")) {
		if err != nil {
			log.Fatal(err) // handle error
		}

		fmt.Println("object:", obj.Key)
	}
}

func (*Client) PresignURL added in v0.5.0

func (c *Client) PresignURL(ctx context.Context, method string, key string, expiry time.Duration, opts ...ClientOption) (string, error)

PresignURL generates a presigned URL for the specified HTTP method, key, and expiry duration.

The following HTTP methods are supported:

  • http.MethodGet: Generate a URL for downloading an object
  • http.MethodPut: Generate a URL for uploading an object
  • http.MethodDelete: Generate a URL for deleting an object

For PUT operations, use WithContentType() and WithContentDisposition() to set headers.

The expiry duration must be positive; the returned URL will only be valid for this duration.

Example (Delete)
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Generate a 30-minute URL for deletion
	url, err := client.PresignURL(ctx, http.MethodDelete, "temp/file.txt", 30*time.Minute)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Println("Presigned DELETE URL:", url)
}
Example (Get)
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Generate a 1-hour URL for temporary download access
	url, err := client.PresignURL(ctx, http.MethodGet, "documents/report.pdf", time.Hour)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Println("Presigned GET URL:", url)
}
Example (Put)
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Generate a 15-minute URL for direct upload
	url, err := client.PresignURL(ctx, http.MethodPut, "uploads/avatar.png", 15*time.Minute,
		simplestorage.WithContentType("image/png"),
		simplestorage.WithContentDisposition("attachment"),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	// Client can now PUT directly to url
	fmt.Println("Presigned PUT URL:", url)
}

func (*Client) Put

func (c *Client) Put(ctx context.Context, obj *Object, opts ...ClientOption) (*Object, error)

Put puts the contents of an object into Tigris.

The returned *Object is the same pointer as obj with Bucket, Key, Etag, and Version populated from the response. When WithRandomSuffix is used, obj.Key is rewritten to the suffixed key actually stored.

Example (NoOverwrite)
package main

import (
	"context"
	"io"
	"log"
	"strings"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	body := strings.NewReader("first write wins")
	_, err = client.Put(ctx, &simplestorage.Object{
		Key:  "config/seed.json",
		Body: io.NopCloser(body),
		Size: int64(body.Len()),
	},
		simplestorage.WithAllowOverwrite(false),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
}
Example (PublicAccess)
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"strings"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	body := strings.NewReader("hello world")
	obj, err := client.Put(ctx, &simplestorage.Object{
		Key:         "public/greeting.txt",
		ContentType: "text/plain",
		Size:        int64(body.Len()),
		Body:        io.NopCloser(body),
	},
		simplestorage.WithAccessType(simplestorage.AccessPublic),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Println(obj.Etag)
}
Example (RandomSuffix)
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"strings"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	body := strings.NewReader("payload")
	// The stored key ends up like "uploads/image.png-<random>" so concurrent
	// uploads with the same base name don't collide.
	obj, err := client.Put(ctx, &simplestorage.Object{
		Key:  "uploads/image.png",
		Body: io.NopCloser(body),
		Size: int64(body.Len()),
	},
		simplestorage.WithRandomSuffix(),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Println(obj.Key)
}
Example (UploadProgress)
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"strings"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	body := strings.NewReader(strings.Repeat("x", 1024))
	_, err = client.Put(ctx, &simplestorage.Object{
		Key:  "reports/large.bin",
		Body: io.NopCloser(body),
		Size: int64(body.Len()),
	},
		simplestorage.WithUploadProgress(func(p simplestorage.UploadProgress) {
			fmt.Printf("uploaded %d of %d bytes (%.1f%%)\n", p.Loaded, p.Total, p.Percentage)
		}),
	)
	if err != nil {
		log.Fatal(err) // handle the error here
	}
}

func (*Client) Snapshot added in v0.7.0

func (c *Client) Snapshot(ctx context.Context, bucket, description string, opts ...BucketOption) (*SnapshotInfo, error)

Snapshot creates a snapshot with the given description for a bucket.

The bucket must have snapshots enabled (created with WithEnableSnapshot()).

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Create a named snapshot
	snapshot, err := client.Snapshot(ctx, "my-bucket", "Backup before migration")
	if err != nil {
		log.Fatal(err) // handle the error here
	}

	fmt.Printf("Created snapshot: %s (version: %s)\n", snapshot.Name, snapshot.Version)
}

func (*Client) Snapshots added in v0.7.0

func (c *Client) Snapshots(ctx context.Context, bucket string, opts ...BucketOption) iter.Seq2[*SnapshotInfo, error]

Snapshots lists all snapshots for the given bucket.

Example
package main

import (
	"context"
	"fmt"
	"log"

	_ "github.com/joho/godotenv/autoload"
	simplestorage "github.com/tigrisdata/storage-go/simplestorage"
)

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

	client, err := simplestorage.New(ctx,
		simplestorage.WithBucket("my-default-bucket"),
	)
	if err != nil {
		log.Fatal(err) // handle error here
	}

	for snapshot, err := range client.Snapshots(ctx, "my-bucket") {
		if err != nil {
			log.Fatal(err) // handle error here
		}
		fmt.Printf("Snapshot: %s (version: %s, created: %s)\n", snapshot.Name, snapshot.Version, snapshot.Created)
	}
}

type ClientOption

type ClientOption func(*ClientOptions)

ClientOption is a function option that allows callers to override settings in calls to Tigris via Client.

func OverrideBucket

func OverrideBucket(bucket string) ClientOption

OverrideBucket overrides the bucket used for Tigris calls.

func WithAccessType added in v0.7.0

func WithAccessType(access AccessType) ClientOption

WithAccessType sets the canned ACL for Put operations. Use AccessPublic to make the uploaded object world-readable or AccessPrivate for authenticated-only access. If unset, the bucket's default ACL applies.

func WithAllowOverwrite added in v0.7.0

func WithAllowOverwrite(allow bool) ClientOption

WithAllowOverwrite controls whether overwrites are permitted in Put operations. When set to false, the operation will fail if the object already exists.

func WithContentDisposition added in v0.5.0

func WithContentDisposition(disposition string) ClientOption

WithContentDisposition sets the Content-Disposition header for Put operations and presigned PUT URLs.

func WithContentType added in v0.5.0

func WithContentType(contentType string) ClientOption

WithContentType sets the Content-Type header. Used by Put (the object Content-Type takes precedence when non-empty) and by presigned PUT URLs.

func WithMultipartUpload added in v0.7.0

func WithMultipartUpload(threshold int64) ClientOption

WithMultipartUpload enables multipart upload for objects whose Size exceeds the given threshold (in bytes).

func WithQuerySnapshotVersion added in v0.7.0

func WithQuerySnapshotVersion(version string) ClientOption

WithQuerySnapshotVersion specifies a snapshot version to query for Get, Head, or List operations. Use this to read from a specific bucket snapshot.

func WithRandomSuffix added in v0.7.0

func WithRandomSuffix() ClientOption

WithRandomSuffix adds a random suffix to the object key for uniqueness in Put operations.

func WithResponseCacheControl added in v0.7.0

func WithResponseCacheControl(cacheControl string) ClientOption

WithResponseCacheControl overrides the Cache-Control header in Get responses.

func WithResponseContentDisposition added in v0.7.0

func WithResponseContentDisposition(disposition string) ClientOption

WithResponseContentDisposition overrides the Content-Disposition header in Get responses.

func WithResponseContentType added in v0.7.0

func WithResponseContentType(contentType string) ClientOption

WithResponseContentType overrides the Content-Type header in Get responses.

func WithS3Options

func WithS3Options(opts ...func(*s3.Options)) ClientOption

WithS3Options sets S3 options for individual Tigris calls.

func WithUploadProgress added in v0.7.0

func WithUploadProgress(callback func(UploadProgress)) ClientOption

WithUploadProgress sets a callback to track upload progress in Put operations.

type ClientOptions

type ClientOptions struct {
	BucketName string
	S3Options  []func(*s3.Options)

	// Put and presign options
	ContentType        *string
	ContentDisposition *string

	// Snapshot version for Get, Head, List operations
	SnapshotVersion *string

	// Response override options for Get operations
	ResponseContentType        *string
	ResponseContentDisposition *string
	ResponseCacheControl       *string

	// Put options
	RandomSuffix           bool
	AllowOverwrite         *bool
	MultipartThreshold     *int64
	UploadProgressCallback func(UploadProgress)
	AccessType             AccessType
}

ClientOptions is the collection of options that are set for individual Tigris calls.

type ListOption added in v0.7.0

type ListOption func(*listOptions)

ListOption configures a single List call. Pass any combination of these to override the default listing behavior.

func WithContinueToken added in v0.7.0

func WithContinueToken(token string) ListOption

WithContinueToken resumes a previous List call from the given continuation token. Use the token returned by the prior page to fetch the next one.

func WithDelimiter added in v0.3.0

func WithDelimiter(delimiter string) ListOption

WithDelimiter groups keys that share a common prefix up to the given delimiter, collapsing them into a single result. The classic value is "/" to emulate directory-style listings.

func WithListS3Options added in v0.7.0

func WithListS3Options(opts ...func(*s3.Options)) ListOption

WithListS3Options appends middleware to the underlying ListObjectsV2 call. Use this to apply Tigris-specific headers to a List call, for example reading from a bucket snapshot:

for obj, err := range client.List(ctx,
	simplestorage.WithListS3Options(tigrisheaders.WithSnapshotVersion("v1")),
) {
	// ...
}

func WithMaxKeys

func WithMaxKeys(maxKeys int32) ListOption

WithMaxKeys caps the number of keys returned per underlying request. This controls page size, not the total number of keys yielded by the iterator.

func WithPrefix added in v0.3.0

func WithPrefix(prefix string) ListOption

WithPrefix restricts the listing to keys that begin with the given prefix.

func WithStartAfter

func WithStartAfter(key string) ListOption

WithStartAfter begins the listing immediately after the given key. The key itself does not need to exist in the bucket; Tigris returns the next key in lexicographic order.

type Object

type Object struct {
	Bucket             string            // Bucket the object is in
	Key                string            // Key for the object
	ContentType        string            // MIME type for the object or application/octet-stream
	ContentDisposition string            // Content disposition of the object (inline or attachment)
	Etag               string            // Entity tag for the object (usually a checksum)
	Version            string            // Version tag for the object
	Size               int64             // Size of the object in bytes or 0 if unknown
	LastModified       time.Time         // Creation date of the object
	Metadata           map[string]string // Custom metadata headers
	URL                string            // Public or presigned URL for the object
	Body               io.ReadCloser     // Body of the object so it can be read, don't forget to close it.
}

Object contains metadata about an individual object read from or put into Tigris.

Some calls may not populate all fields. Ensure that the values are valid before consuming them.

type Option

type Option func(o *Options)

Option is a functional option for new client creation.

func WithAccessKeypair

func WithAccessKeypair(accessKeyID, secretAccessKey string) Option

WithAccessKeypair lets you specify a custom access key and secret access key for interfacing with Tigris.

This is useful when you need to load environment variables from somewhere other than the default AWS configuration path.

func WithBucket

func WithBucket(bucketName string) Option

WithBucket sets the default bucket for Tigris operations. If this is not set via the `TIGRIS_STORAGE_BUCKET` environment variable or this call, New() will return ErrNoBucketName.

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint sets a custom endpoint for connecting to Tigris.

This allows you to connect to a custom Tigris endpoint instead of the default global endpoint. Use this for:

  • Using a custom proxy or gateway
  • Testing against local development endpoints

For most use cases, consider using WithGlobalEndpoint or WithFlyEndpoint instead.

func WithFlyEndpoint

func WithFlyEndpoint() Option

WithFlyEndpoint lets you connect to Tigris' fly.io optimized endpoint.

If you are deployed to fly.io, this zero-rates your traffic to Tigris.

If you are not deployed to fly.io, please use WithGlobalEndpoint instead.

func WithGlobalEndpoint

func WithGlobalEndpoint() Option

WithGlobalEndpoint lets you connect to Tigris' globally available endpoint.

If you are deployed to fly.io, please use WithFlyEndpoint instead.

func WithPathStyle

func WithPathStyle(enabled bool) Option

WithPathStyle configures whether to use path-style addressing for S3 requests.

By default, Tigris uses virtual-hosted-style addressing (e.g., https://bucket.t3.storage.dev). Path-style addressing (e.g., https://t3.storage.dev/bucket) may be needed for:

  • Compatibility with older S3 clients that don't support virtual-hosted-style
  • Working through certain proxies or load balancers that don't support virtual-hosted-style
  • Local development environments with custom DNS setups

Enable this only if you encounter issues with the default virtual-hosted-style addressing.

func WithRegion

func WithRegion(region string) Option

WithRegion lets you statically specify a region for interacting with Tigris.

You will almost certainly never need this. This is here for development usecases where the default region is not "auto".

type Options

type Options struct {
	// The bucket to operate against. Defaults to the contents of the environment variable
	// `TIGRIS_STORAGE_BUCKET`.
	BucketName string

	// The access key ID of the Tigris keypair the Client should use. Defaults to the contents
	// of the environment variable `TIGRIS_STORAGE_ACCESS_KEY_ID`.
	AccessKeyID string

	// The access key ID of the Tigris keypair the Client should use. Defaults to the contents
	// of the environment variable `TIGRIS_STORAGE_SECRET_ACCESS_KEY`.
	SecretAccessKey string

	BaseEndpoint string // The Tigris base endpoint the Client should use (defaults to GlobalEndpoint)
	Region       string // The S3 region the Client should use (defaults to "auto").
	UsePathStyle bool   // Should the Client use S3 path style resolution? (defaults to false).
}

Options is the set of options for client creation.

These fields are made public so you can implement your own configuration resolution methods.

type SnapshotInfo

type SnapshotInfo struct {
	Name    string    // Snapshot name/description
	Version string    // Snapshot version ID
	Created time.Time // Creation time
	Bucket  string    // Source bucket name
}

SnapshotInfo contains metadata about a bucket snapshot.

type UploadProgress added in v0.7.0

type UploadProgress struct {
	Loaded     int64   // Bytes uploaded
	Total      int64   // Total bytes
	Percentage float64 // Percentage complete
}

UploadProgress tracks upload progress.

Jump to

Keyboard shortcuts

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