simples3

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2025 License: BSD-2-Clause Imports: 26 Imported by: 7

README

simples3 : Simple no frills AWS S3 Library using REST with V4 Signing

Overview GoDoc Go Report Card GoCover Zerodha Tech

SimpleS3 is a Go library for manipulating objects in S3 buckets using REST API calls or Presigned URLs signed using AWS Signature Version 4.

Features:

  • Simple, intuitive API following Go idioms
  • Complete S3 operations - Upload, Download, Delete, List, Details
  • Multipart upload - Large file support with parallel uploads, progress tracking, and resumability
  • Bucket management - Create, Delete, and List buckets
  • AWS Signature Version 4 signing
  • Custom endpoint support (MinIO, DigitalOcean Spaces, etc.)
  • Simple List API with pagination, prefix filtering, and delimiter grouping
  • Iterator-based ListAll for memory-efficient large bucket iteration (Go 1.23+)
  • Presigned URL generation for secure browser uploads/downloads (including multipart)
  • Object Versioning - Enable versioning, list versions, and access specific object versions
  • Server-Side Encryption - Support for SSE-S3 (AES256) and SSE-KMS encryption
  • IAM credential support for EC2 instances
  • Comprehensive test coverage
  • Zero dependencies - uses only Go standard library

Install

go get github.com/rhnvrm/simples3

Quick Start

package main

import (
    "log"
    "os"
    "github.com/rhnvrm/simples3"
)

func main() {
    // Initialize S3 client
    s3 := simples3.New("us-east-1", "your-access-key", "your-secret-key")

    // Upload a file
    file, err := os.Open("my-file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    resp, err := s3.FileUpload(simples3.UploadInput{
        Bucket:      "my-bucket",
        ObjectKey:   "my-file.txt",
        ContentType: "text/plain",
        FileName:    "my-file.txt",
        Body:        file,
    })
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("File uploaded successfully: %+v", resp)
}

API Reference

Bucket Operations
List All Buckets
// List all buckets for the AWS account
result, err := s3.ListBuckets(simples3.ListBucketsInput{})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Found %d buckets:\n", len(result.Buckets))
for _, bucket := range result.Buckets {
    fmt.Printf("- %s (created: %s)\n", bucket.Name, bucket.CreationDate)
}

// Owner information is also available
fmt.Printf("Owner: %s (%s)\n", result.Owner.DisplayName, result.Owner.ID)
Create a Bucket
// Create a new bucket
output, err := s3.CreateBucket(simples3.CreateBucketInput{
    Bucket: "my-new-bucket",
    Region: "us-east-1", // Optional, defaults to client region
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Bucket created at: %s\n", output.Location)
Delete a Bucket
// Delete an empty bucket
err := s3.DeleteBucket(simples3.DeleteBucketInput{
    Bucket: "my-old-bucket",
})
if err != nil {
    log.Fatal(err)
}

// Note: The bucket must be empty before deletion
File Operations
Upload Files
// POST upload (recommended for browsers)
resp, err := s3.FileUpload(simples3.UploadInput{
    Bucket:      "my-bucket",
    ObjectKey:   "path/to/file.txt",
    ContentType: "text/plain",
    FileName:    "file.txt",
    Body:        file,
})

// PUT upload (simpler for programmatic use)
resp, err := s3.FilePut(simples3.UploadInput{
    Bucket:      "my-bucket",
    ObjectKey:   "path/to/file.txt",
    ContentType: "text/plain",
    Body:        file,
})
Download Files
// Download file
file, err := s3.FileDownload(simples3.DownloadInput{
    Bucket:    "my-bucket",
    ObjectKey: "path/to/file.txt",
})
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// Read the content
data, err := io.ReadAll(file)
if err != nil {
    log.Fatal(err)
}
Delete Files
err := s3.FileDelete(simples3.DeleteInput{
    Bucket:    "my-bucket",
    ObjectKey: "path/to/file.txt",
})
Copy Objects
// Copy object within same bucket
output, err := s3.CopyObject(simples3.CopyObjectInput{
    SourceBucket: "my-bucket",
    SourceKey:    "original/file.txt",
    DestBucket:   "my-bucket",
    DestKey:      "copied/file.txt",
})

// Copy across buckets
output, err := s3.CopyObject(simples3.CopyObjectInput{
    SourceBucket: "source-bucket",
    SourceKey:    "file.txt",
    DestBucket:   "dest-bucket",
    DestKey:      "file.txt",
})

// Copy with metadata replacement
output, err := s3.CopyObject(simples3.CopyObjectInput{
    SourceBucket:      "my-bucket",
    SourceKey:         "file.txt",
    DestBucket:        "my-bucket",
    DestKey:           "file-copy.txt",
    MetadataDirective: "REPLACE",
    ContentType:       "application/json",
    CustomMetadata:    map[string]string{"version": "2"},
})
Batch Delete Files
// Delete multiple objects in one request (up to 1000)
output, err := s3.DeleteObjects(simples3.DeleteObjectsInput{
    Bucket:  "my-bucket",
    Objects: []string{"file1.txt", "file2.txt", "file3.txt"},
    Quiet:   false,
})
if err != nil {
    log.Fatal(err)
}

// Check results
for _, deleted := range output.Deleted {
    fmt.Printf("Deleted: %s\n", deleted.Key)
}
for _, errItem := range output.Errors {
    fmt.Printf("Failed to delete %s: %s\n", errItem.Key, errItem.Message)
}
Get File Details
details, err := s3.FileDetails(simples3.DetailsInput{
    Bucket:    "my-bucket",
    ObjectKey: "path/to/file.txt",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("File size: %s bytes", details.ContentLength)
log.Printf("Last modified: %s", details.LastModified)
log.Printf("Content type: %s", details.ContentType)
List Objects

SimpleS3 provides a clean, easy-to-use List API that follows the same pattern as other library methods:

Simple Listing
// List all objects in a bucket
result, err := s3.List(simples3.ListInput{
    Bucket: "my-bucket",
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Found %d objects:\n", len(result.Objects))
for _, obj := range result.Objects {
    fmt.Printf("- %s (%d bytes)\n", obj.Key, obj.Size)
}
Advanced Listing with Options
// List with prefix filtering and pagination
result, err := s3.List(simples3.ListInput{
    Bucket:    "my-bucket",
    Prefix:    "documents/",
    Delimiter: "/",
    MaxKeys:   100,
})
if err != nil {
    log.Fatal(err)
}

// Process objects
for _, obj := range result.Objects {
    fmt.Printf("%s (%d bytes)\n", obj.Key, obj.Size)
}

// Process "directories" (common prefixes)
for _, prefix := range result.CommonPrefixes {
    fmt.Printf("%s/\n", prefix)
}
Iterator-based Listing (Go 1.23+)
// Use the new ListAll method for memory-efficient iteration
s3 := simples3.New("us-east-1", "your-access-key", "your-secret-key")

// Iterate over all objects with automatic pagination and error handling
seq, finish := s3.ListAll(simples3.ListInput{
    Bucket: "my-bucket",
    Prefix: "documents/", // Optional filtering
})

for obj := range seq {
    fmt.Printf("%s (%d bytes)\n", obj.Key, obj.Size)
}

// Check for any errors that occurred during iteration
if err := finish(); err != nil {
    log.Fatalf("Error during iteration: %v", err)
}
Handle Pagination (Legacy)
// Handle large result sets with pagination
func listAllObjects(s3 *simples3.S3, bucket string) ([]simples3.Object, error) {
    var allObjects []simples3.Object
    var continuationToken string

    for {
        // List objects with continuation token
        result, err := s3.List(simples3.ListInput{
            Bucket:            bucket,
            ContinuationToken: continuationToken,
            MaxKeys:          1000, // Maximum page size
        })
        if err != nil {
            return nil, err
        }

        // Add current page objects to our collection
        allObjects = append(allObjects, result.Objects...)

        // Check if there are more pages
        if !result.IsTruncated {
            break
        }

        // Set token for next page
        continuationToken = result.NextContinuationToken
    }

    return allObjects, nil
}

// Usage example
func main() {
    s3 := simples3.New("us-east-1", "your-access-key", "your-secret-key")

    allObjects, err := listAllObjects(s3, "my-bucket")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Total objects: %d\n", len(allObjects))
    for _, obj := range allObjects {
        fmt.Printf("- %s (%d bytes)\n", obj.Key, obj.Size)
    }
}
Object Tagging

S3 object tags are key-value pairs that you can use to categorize, organize, and manage objects. Each object can have up to 10 tags.

Put Tags on an Object

Set or replace all tags on an existing object:

err := s3.PutObjectTagging(simples3.PutObjectTaggingInput{
    Bucket:    "my-bucket",
    ObjectKey: "my-file.txt",
    Tags: map[string]string{
        "Environment": "production",
        "Project":     "website",
        "Version":     "v1.2.0",
    },
})
if err != nil {
    log.Fatal(err)
}
Get Tags from an Object

Retrieve all tags from an object:

output, err := s3.GetObjectTagging(simples3.GetObjectTaggingInput{
    Bucket:    "my-bucket",
    ObjectKey: "my-file.txt",
})
if err != nil {
    log.Fatal(err)
}

for key, value := range output.Tags {
    fmt.Printf("%s: %s\n", key, value)
}
Delete All Tags from an Object

Remove all tags from an object:

err := s3.DeleteObjectTagging(simples3.DeleteObjectTaggingInput{
    Bucket:    "my-bucket",
    ObjectKey: "my-file.txt",
})
if err != nil {
    log.Fatal(err)
}
Upload with Tags

You can set tags when uploading an object using FilePut:

_, err := s3.FilePut(simples3.UploadInput{
    Bucket:      "my-bucket",
    ObjectKey:   "my-file.txt",
    ContentType: "text/plain",
    Body:        file,
    Tags: map[string]string{
        "Environment": "production",
        "Department":  "engineering",
    },
})

Note: Tag support during upload varies by operation:

  • FilePut (PUT): ✅ Full support
  • FileUpload (POST): ⚠️ AWS S3 supported, MinIO limited (does not support tags in POST policy)
  • CopyObject: ✅ Full support (handles MinIO/R2 signature quirks automatically)
Object Versioning

Enable and manage object versions to protect against accidental deletion or overwrite.

Enable Versioning
err := s3.PutBucketVersioning(simples3.PutBucketVersioningInput{
    Bucket: "my-bucket",
    Status: "Enabled", // or "Suspended"
})
if err != nil {
    log.Fatal(err)
}

// Check status
config, err := s3.GetBucketVersioning("my-bucket")
fmt.Printf("Versioning status: %s\n", config.Status)
List Object Versions

List all versions of objects in a bucket:

result, err := s3.ListVersions(simples3.ListVersionsInput{
    Bucket: "my-bucket",
    Prefix: "important-file.txt",
})
if err != nil {
    log.Fatal(err)
}

for _, version := range result.Versions {
    fmt.Printf("Key: %s, VersionId: %s, IsLatest: %v\n",
        version.Key, version.VersionId, version.IsLatest)
}
Download Specific Version

Retrieve a specific version of an object:

file, err := s3.FileDownload(simples3.DownloadInput{
    Bucket:    "my-bucket",
    ObjectKey: "my-file.txt",
    VersionId: "v1-version-id",
})
if err != nil {
    log.Fatal(err)
}
// Use file (io.ReadCloser) normally
Delete Specific Version

Delete a specific version of an object:

err := s3.FileDelete(simples3.DeleteInput{
    Bucket:    "my-bucket",
    ObjectKey: "my-file.txt",
    VersionId: "v1-version-id",
})
Server-Side Encryption

Secure your data at rest using Server-Side Encryption (SSE). SimpleS3 supports both SSE-S3 (AES256) and SSE-KMS.

Upload with SSE-S3 (AES256)
_, err := s3.FilePut(simples3.UploadInput{
    Bucket:               "my-bucket",
    ObjectKey:            "secure-file.txt",
    Body:                 strings.NewReader("secret data"),
    ServerSideEncryption: "AES256",
})
Upload with SSE-KMS
_, err := s3.FilePut(simples3.UploadInput{
    Bucket:               "my-bucket",
    ObjectKey:            "kms-encrypted-file.txt",
    Body:                 strings.NewReader("secret data"),
    ServerSideEncryption: "aws:kms",
    SSEKMSKeyId:          "arn:aws:kms:us-east-1:123456789012:key/your-key-id",
})
Multipart Upload with Encryption
output, err := s3.FileUploadMultipart(simples3.MultipartUploadInput{
    Bucket:               "my-bucket",
    ObjectKey:            "large-secure-file.mp4",
    Body:                 file,
    ServerSideEncryption: "AES256",
})
Copy with Encryption
_, err := s3.CopyObject(simples3.CopyObjectInput{
    SourceBucket:         "my-bucket",
    SourceKey:            "original.txt",
    DestBucket:           "my-bucket",
    DestKey:              "encrypted-copy.txt",
    ServerSideEncryption: "AES256",
})
Check Encryption Status
details, err := s3.FileDetails(simples3.DetailsInput{
    Bucket:    "my-bucket",
    ObjectKey: "secure-file.txt",
})

fmt.Printf("Encryption: %s\n", details.ServerSideEncryption)
if details.SSEKMSKeyId != "" {
    fmt.Printf("KMS Key ID: %s\n", details.SSEKMSKeyId)
}
Multipart Upload

For large files (>100MB), use multipart upload for better performance, resumability, and parallel uploads.

The easiest way to upload large files:

file, err := os.Open("large-video.mp4")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// FileUploadMultipart automatically handles chunking and parallel uploads
output, err := s3.FileUploadMultipart(simples3.MultipartUploadInput{
    Bucket:      "my-bucket",
    ObjectKey:   "videos/large-video.mp4",
    Body:        file,
    ContentType: "video/mp4",
    PartSize:    10 * 1024 * 1024, // 10MB parts (optional, default 5MB)
    Concurrency: 5,                 // Upload 5 parts in parallel (optional, default 1)
    OnProgress: func(info simples3.ProgressInfo) {
        fmt.Printf("\rProgress: %.1f%% (%d/%d parts)",
            float64(info.UploadedBytes)/float64(info.TotalBytes)*100,
            info.CurrentPart, info.TotalParts)
    },
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("\nUploaded: %s (ETag: %s)\n", output.Key, output.ETag)
Low-Level API (Advanced)

For more control over the upload process:

// 1. Initiate multipart upload
initOutput, err := s3.InitiateMultipartUpload(simples3.InitiateMultipartUploadInput{
    Bucket:      "my-bucket",
    ObjectKey:   "large-file.bin",
    ContentType: "application/octet-stream",
})
if err != nil {
    log.Fatal(err)
}

// 2. Upload parts (can be done in parallel or resumed later)
var completedParts []simples3.CompletedPart
partSize := int64(10 * 1024 * 1024) // 10MB

for partNum := 1; partNum <= totalParts; partNum++ {
    // Read part data
    partData := getPartData(partNum, partSize) // Your function to get part data

    output, err := s3.UploadPart(simples3.UploadPartInput{
        Bucket:     "my-bucket",
        ObjectKey:  "large-file.bin",
        UploadID:   initOutput.UploadID,
        PartNumber: partNum,
        Body:       bytes.NewReader(partData),
        Size:       int64(len(partData)),
    })
    if err != nil {
        // Abort on error
        s3.AbortMultipartUpload(simples3.AbortMultipartUploadInput{
            Bucket:    "my-bucket",
            ObjectKey: "large-file.bin",
            UploadID:  initOutput.UploadID,
        })
        log.Fatal(err)
    }

    completedParts = append(completedParts, simples3.CompletedPart{
        PartNumber: output.PartNumber,
        ETag:       output.ETag,
    })
}

// 3. Complete the upload
result, err := s3.CompleteMultipartUpload(simples3.CompleteMultipartUploadInput{
    Bucket:    "my-bucket",
    ObjectKey: "large-file.bin",
    UploadID:  initOutput.UploadID,
    Parts:     completedParts,
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Upload completed: %s\n", result.ETag)
List Uploaded Parts

Query which parts have been uploaded (useful for resuming uploads):

output, err := s3.ListParts(simples3.ListPartsInput{
    Bucket:    "my-bucket",
    ObjectKey: "large-file.bin",
    UploadID:  uploadID,
})
if err != nil {
    log.Fatal(err)
}

for _, part := range output.Parts {
    fmt.Printf("Part %d: %d bytes (ETag: %s)\n",
        part.PartNumber, part.Size, part.ETag)
}
Abort Multipart Upload

Cancel an in-progress upload and clean up parts:

err := s3.AbortMultipartUpload(simples3.AbortMultipartUploadInput{
    Bucket:    "my-bucket",
    ObjectKey: "large-file.bin",
    UploadID:  uploadID,
})
Browser-Based Multipart Upload

Generate presigned URLs for each part to enable direct browser uploads:

// Backend: Initiate and generate presigned URLs
initOutput, _ := s3.InitiateMultipartUpload(simples3.InitiateMultipartUploadInput{
    Bucket:    "my-bucket",
    ObjectKey: "client-upload.bin",
})

// Generate presigned URL for part 1
presignedURL := s3.GeneratePresignedUploadPartURL(simples3.PresignedMultipartInput{
    Bucket:        "my-bucket",
    ObjectKey:     "client-upload.bin",
    UploadID:      initOutput.UploadID,
    PartNumber:    1,
    ExpirySeconds: 3600,
})

// Frontend: Upload directly to S3 using the presigned URL (via PUT request)
// Then send ETags back to backend for completion
Presigned URLs

Generate secure URLs for browser-based uploads/downloads:

// Generate presigned URL for download
url := s3.GeneratePresignedURL(simples3.PresignedInput{
    Bucket:        "my-bucket",
    ObjectKey:     "private-file.pdf",
    Method:        "GET",
    ExpirySeconds: 3600, // 1 hour
})

// Users can now download directly: <a href="{{url}}">Download</a>
Custom Endpoints

Use with MinIO, DigitalOcean Spaces, or other S3-compatible services:

// MinIO
s3 := simples3.New("us-east-1", "minioadmin", "minioadmin")
s3.SetEndpoint("http://localhost:9000")

// DigitalOcean Spaces
s3 := simples3.New("nyc3", "your-access-key", "your-secret-key")
s3.SetEndpoint("https://nyc3.digitaloceanspaces.com")
IAM Credentials

On EC2 instances, use IAM roles automatically:

s3, err := simples3.NewUsingIAM("us-east-1")
if err != nil {
    log.Fatal(err)
}
// Automatically uses instance IAM role

Development

Setup Development Environment
# Clone the repository
git clone https://github.com/rhnvrm/simples3.git
cd simples3

# Using Nix (recommended)
nix develop

# Or using direnv
direnv allow

# Start local MinIO for testing
just setup

# Run tests
just test-local
Testing

The library includes comprehensive tests that run against a local MinIO instance:

# Run all tests (without MinIO)
just test

# Run tests with local MinIO
just test-local

# Run specific test
go test -v -run TestList
Available Commands
just              # List all commands
just test         # Run tests without MinIO
just test-local   # Run tests with MinIO (includes setup)
just setup        # Setup development environment
just minio-up      # Start MinIO container
just minio-down    # Stop MinIO container
just clean         # Clean up everything
just status        # Check development environment status

Environment Variables

For development and testing:

export AWS_S3_REGION="us-east-1"
export AWS_S3_ACCESS_KEY="minioadmin"
export AWS_S3_SECRET_KEY="minioadmin"
export AWS_S3_ENDPOINT="http://localhost:9000"
export AWS_S3_BUCKET="testbucket"

Contributing

Contributions welcome! Check ROADMAP.md for planned features. Please add tests and ensure just test-local passes before submitting PRs.

Author

Rohan Verma hello@rohanverma.net

License

BSD-2-Clause-FreeBSD

Documentation

Index

Constants

View Source
const (
	MinPartSize          = 5 * 1024 * 1024        // 5 MB
	MaxPartSize          = 5 * 1024 * 1024 * 1024 // 5 GB
	MaxParts             = 10000
	DefaultPartSize      = 5 * 1024 * 1024 // 5 MB
	DefaultMaxRetries    = 3
	DefaultRetryBaseWait = 100 * time.Millisecond
	DefaultRetryMaxWait  = 5 * time.Second
)

Multipart upload constants

View Source
const (
	// AMZMetaPrefix to prefix metadata key.
	AMZMetaPrefix = "x-amz-meta-"
)
View Source
const (
	HdrXAmzSignedHeaders = "X-Amz-SignedHeaders"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AbortMultipartUploadInput added in v0.11.0

type AbortMultipartUploadInput struct {
	Bucket    string // Required: bucket name
	ObjectKey string // Required: object key
	UploadID  string // Required: upload ID
}

AbortMultipartUploadInput contains parameters for aborting a multipart upload

type AccessControlPolicy added in v0.11.0

type AccessControlPolicy struct {
	XMLName           xml.Name `xml:"AccessControlPolicy"`
	XMLNS             string   `xml:"xmlns,attr,omitempty"`
	Owner             Owner    `xml:"Owner"`
	AccessControlList []Grant  `xml:"AccessControlList>Grant"`
}

AccessControlPolicy represents the Access Control List (ACL) for a bucket or object.

type Bucket added in v0.11.0

type Bucket struct {
	Name         string    `xml:"Name"`
	CreationDate time.Time `xml:"CreationDate"`
}

Bucket represents a single S3 bucket.

type CompleteMultipartUploadInput added in v0.11.0

type CompleteMultipartUploadInput struct {
	Bucket    string          // Required: bucket name
	ObjectKey string          // Required: object key
	UploadID  string          // Required: upload ID
	Parts     []CompletedPart // Required: list of parts, ordered by PartNumber
}

CompleteMultipartUploadInput contains parameters for completing a multipart upload

type CompleteMultipartUploadOutput added in v0.11.0

type CompleteMultipartUploadOutput struct {
	Location string
	Bucket   string
	Key      string
	ETag     string
}

CompleteMultipartUploadOutput contains the response from completing a multipart upload

type CompletedPart added in v0.11.0

type CompletedPart struct {
	PartNumber int
	ETag       string
}

CompletedPart represents a part that has been uploaded

type CopyObjectInput added in v0.11.0

type CopyObjectInput struct {
	// Required: Source bucket name
	SourceBucket string

	// Required: Source object key
	SourceKey string

	// Required: Destination bucket name
	DestBucket string

	// Required: Destination object key
	DestKey string

	// Optional: COPY (default) or REPLACE
	// COPY - copies metadata from source
	// REPLACE - replaces metadata with values specified in this input
	MetadataDirective string

	// Optional: Content type (only used when MetadataDirective = REPLACE)
	ContentType string

	// Optional: Custom metadata (only used when MetadataDirective = REPLACE)
	CustomMetadata map[string]string

	// Optional: Tags to set on the destination object (max 10 tags)
	// When set, uses x-amz-tagging-directive: REPLACE
	Tags map[string]string

	// Optional: Server-side encryption (e.g. "AES256" or "aws:kms")
	ServerSideEncryption string

	// Optional: KMS Key ID (ARN or ID) when ServerSideEncryption is "aws:kms"
	SSEKMSKeyId string
}

CopyObjectInput is passed to CopyObject as a parameter.

type CopyObjectOutput added in v0.11.0

type CopyObjectOutput struct {
	ETag         string
	LastModified time.Time
}

CopyObjectOutput is returned by CopyObject.

type CreateBucketInput added in v0.11.0

type CreateBucketInput struct {
	// Required: The name of the bucket to create
	Bucket string

	// Optional: AWS region for the bucket.
	// If empty, uses the region from S3 struct.
	// Note: For us-east-1, no LocationConstraint is needed.
	Region string
}

CreateBucketInput is passed to CreateBucket as a parameter.

type CreateBucketOutput added in v0.11.0

type CreateBucketOutput struct {
	// Location header from the response
	Location string
}

CreateBucketOutput is returned by CreateBucket.

type DeleteBucketInput added in v0.11.0

type DeleteBucketInput struct {
	// Required: The name of the bucket to delete
	// Note: The bucket must be empty before deletion
	Bucket string
}

DeleteBucketInput is passed to DeleteBucket as a parameter.

type DeleteError added in v0.11.0

type DeleteError struct {
	Key     string `xml:"Key"`
	Code    string `xml:"Code"`
	Message string `xml:"Message"`
}

DeleteError represents a deletion error.

type DeleteInput

type DeleteInput struct {
	Bucket    string
	ObjectKey string
	VersionId string // Optional: Version ID of the object to delete
}

DeleteInput is passed to FileDelete as a parameter.

type DeleteMarker added in v0.11.0

type DeleteMarker struct {
	IsLatest     bool   `xml:"IsLatest"`
	Key          string `xml:"Key"`
	LastModified string `xml:"LastModified"`
	VersionId    string `xml:"VersionId"`
	Owner        struct {
		ID          string `xml:"ID"`
		DisplayName string `xml:"DisplayName"`
	} `xml:"Owner"`
}

DeleteMarker represents a delete marker for an object.

type DeleteObjectTaggingInput added in v0.11.0

type DeleteObjectTaggingInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: The object key
	ObjectKey string
}

DeleteObjectTaggingInput is passed to DeleteObjectTagging as a parameter.

type DeleteObjectsInput added in v0.11.0

type DeleteObjectsInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: List of object keys to delete (max 1000)
	Objects []string

	// Optional: Quiet mode - only return errors, not successes
	Quiet bool
}

DeleteObjectsInput is passed to DeleteObjects as a parameter.

type DeleteObjectsOutput added in v0.11.0

type DeleteObjectsOutput struct {
	Deleted []DeletedObject
	Errors  []DeleteError
}

DeleteObjectsOutput is returned by DeleteObjects.

type DeletedObject added in v0.11.0

type DeletedObject struct {
	Key string `xml:"Key"`
}

DeletedObject represents a successfully deleted object.

type DetailsInput added in v0.7.0

type DetailsInput struct {
	Bucket    string
	ObjectKey string
	VersionId string // Optional: Version ID of the object to retrieve details for
}

DetailsInput is passed to FileDetails as a parameter.

type DetailsResponse added in v0.7.0

type DetailsResponse struct {
	ContentType   string
	ContentLength string
	AcceptRanges  string
	Date          string
	Etag          string
	LastModified  string
	Server        string
	AmzID2        string
	AmzRequestID  string
	// Server-side encryption (e.g. "AES256" or "aws:kms")
	ServerSideEncryption string
	// KMS Key ID (ARN or ID) when ServerSideEncryption is "aws:kms"
	SSEKMSKeyId  string
	AmzMeta      map[string]string
	ExtraHeaders map[string]string
}

DetailsResponse is returned by FileDetails.

type DownloadInput added in v0.5.0

type DownloadInput struct {
	Bucket    string
	ObjectKey string
	VersionId string // Optional: Version ID of the object to download
}

type GetBucketVersioningOutput added in v0.11.0

type GetBucketVersioningOutput struct {
	Status    string
	MfaDelete string
}

GetBucketVersioningOutput is returned by GetBucketVersioning.

type GetObjectAclInput added in v0.11.0

type GetObjectAclInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: The object key
	ObjectKey string

	// Optional: Version ID of the object
	VersionId string
}

GetObjectAclInput is passed to GetObjectAcl.

type GetObjectTaggingInput added in v0.11.0

type GetObjectTaggingInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: The object key
	ObjectKey string
}

GetObjectTaggingInput is passed to GetObjectTagging as a parameter.

type GetObjectTaggingOutput added in v0.11.0

type GetObjectTaggingOutput struct {
	Tags map[string]string
}

GetObjectTaggingOutput is returned by GetObjectTagging.

type Grant added in v0.11.0

type Grant struct {
	Grantee    Grantee `xml:"Grantee"`
	Permission string  `xml:"Permission"`
}

Grant represents a permission grant.

type Grantee added in v0.11.0

type Grantee struct {
	XMLNS        string `xml:"xmlns:xsi,attr,omitempty"`
	Type         string `xml:"xsi:type,attr"` // CanonicalUser, AmazonCustomerByEmail, Group
	ID           string `xml:"ID,omitempty"`
	DisplayName  string `xml:"DisplayName,omitempty"`
	URI          string `xml:"URI,omitempty"`          // For Group
	EmailAddress string `xml:"EmailAddress,omitempty"` // For AmazonCustomerByEmail
}

Grantee represents the recipient of the permission grant.

type IAMResponse

type IAMResponse struct {
	Code            string    `json:"Code"`
	LastUpdated     string    `json:"LastUpdated"`
	Type            string    `json:"Type"`
	AccessKeyID     string    `json:"AccessKeyId"`
	SecretAccessKey string    `json:"SecretAccessKey"`
	Token           string    `json:"Token"`
	Expiration      time.Time `json:"Expiration"`
}

IAMResponse is used by NewUsingIAM to auto detect the credentials.

type InitiateMultipartUploadInput added in v0.11.0

type InitiateMultipartUploadInput struct {
	Bucket         string            // Required: bucket name
	ObjectKey      string            // Required: object key
	ContentType    string            // Optional: content type
	CustomMetadata map[string]string // Optional: x-amz-meta-* headers
	ACL            string            // Optional: x-amz-acl

	// Optional: Server-side encryption (e.g. "AES256" or "aws:kms")
	ServerSideEncryption string
	// Optional: KMS Key ID (ARN or ID) when ServerSideEncryption is "aws:kms"
	SSEKMSKeyId string
}

InitiateMultipartUploadInput contains parameters for initiating a multipart upload

type InitiateMultipartUploadOutput added in v0.11.0

type InitiateMultipartUploadOutput struct {
	Bucket   string
	Key      string
	UploadID string
}

InitiateMultipartUploadOutput contains the response from initiating a multipart upload

type LifecycleAbortIncompleteMultipartUpload added in v0.11.0

type LifecycleAbortIncompleteMultipartUpload struct {
	DaysAfterInitiation int `xml:"DaysAfterInitiation"`
}

LifecycleAbortIncompleteMultipartUpload represents abort action for incomplete uploads.

type LifecycleConfiguration added in v0.11.0

type LifecycleConfiguration struct {
	XMLName xml.Name        `xml:"LifecycleConfiguration"`
	XMLNS   string          `xml:"xmlns,attr,omitempty"`
	Rules   []LifecycleRule `xml:"Rule"`
}

LifecycleConfiguration represents the lifecycle configuration for a bucket.

type LifecycleExpiration added in v0.11.0

type LifecycleExpiration struct {
	Date                      string `xml:"Date,omitempty"` // ISO 8601 format
	Days                      int    `xml:"Days,omitempty"`
	ExpiredObjectDeleteMarker bool   `xml:"ExpiredObjectDeleteMarker,omitempty"`
}

LifecycleExpiration represents the expiration action.

type LifecycleFilter added in v0.11.0

type LifecycleFilter struct {
	Prefix string `xml:"Prefix,omitempty"`
	Tag    *Tag   `xml:"Tag,omitempty"`
	And    *struct {
		Prefix string `xml:"Prefix,omitempty"`
		Tags   []Tag  `xml:"Tag,omitempty"`
	} `xml:"And,omitempty"`
}

LifecycleFilter represents the filter for a lifecycle rule.

type LifecycleNoncurrentVersionExpiration added in v0.11.0

type LifecycleNoncurrentVersionExpiration struct {
	NoncurrentDays int `xml:"NoncurrentDays"`
}

LifecycleNoncurrentVersionExpiration represents expiration for noncurrent versions.

type LifecycleNoncurrentVersionTransition added in v0.11.0

type LifecycleNoncurrentVersionTransition struct {
	NoncurrentDays int    `xml:"NoncurrentDays"`
	StorageClass   string `xml:"StorageClass"`
}

LifecycleNoncurrentVersionTransition represents transition for noncurrent versions.

type LifecycleRule added in v0.11.0

type LifecycleRule struct {
	ID     string           `xml:"ID,omitempty"`
	Status string           `xml:"Status"` // Enabled or Disabled
	Filter *LifecycleFilter `xml:"Filter,omitempty"`
	// Legacy Prefix support (S3 supports both, but prefer Filter for V2)
	// If Prefix is provided here, do not use Filter.
	Prefix                         *string                                  `xml:"Prefix,omitempty"`
	Expiration                     *LifecycleExpiration                     `xml:"Expiration,omitempty"`
	Transitions                    []LifecycleTransition                    `xml:"Transition,omitempty"`
	NoncurrentVersionExpiration    *LifecycleNoncurrentVersionExpiration    `xml:"NoncurrentVersionExpiration,omitempty"`
	NoncurrentVersionTransitions   []LifecycleNoncurrentVersionTransition   `xml:"NoncurrentVersionTransition,omitempty"`
	AbortIncompleteMultipartUpload *LifecycleAbortIncompleteMultipartUpload `xml:"AbortIncompleteMultipartUpload,omitempty"`
}

LifecycleRule represents a single lifecycle rule.

type LifecycleTransition added in v0.11.0

type LifecycleTransition struct {
	Date         string `xml:"Date,omitempty"`
	Days         int    `xml:"Days,omitempty"`
	StorageClass string `xml:"StorageClass"`
}

LifecycleTransition represents a transition action.

type ListBucketsInput added in v0.11.0

type ListBucketsInput struct {
}

ListBucketsInput is passed to ListBuckets as a parameter.

type ListBucketsOutput added in v0.11.0

type ListBucketsOutput struct {
	Buckets []Bucket `xml:"Buckets>Bucket"`
	Owner   struct {
		ID          string `xml:"ID"`
		DisplayName string `xml:"DisplayName"`
	} `xml:"Owner"`
}

ListBucketsOutput is returned by ListBuckets.

type ListInput added in v0.10.0

type ListInput struct {
	// Required: The name of the bucket to list objects from
	Bucket string

	// Optional: A delimiter to group objects by (commonly "/")
	Delimiter string

	// Optional: Only list objects starting with this prefix
	Prefix string

	// Optional: Maximum number of objects to return
	MaxKeys int64

	// Optional: Token for pagination from a previous request
	ContinuationToken string

	// Optional: Object key to start listing after
	StartAfter string
}

ListInput is passed to List as a parameter.

type ListPartsInput added in v0.11.0

type ListPartsInput struct {
	Bucket           string // Required: bucket name
	ObjectKey        string // Required: object key
	UploadID         string // Required: upload ID
	MaxParts         int    // Optional: default 1000, max 1000
	PartNumberMarker int    // Optional: for pagination
}

ListPartsInput contains parameters for listing parts

type ListPartsOutput added in v0.11.0

type ListPartsOutput struct {
	Bucket               string
	Key                  string
	UploadID             string
	Parts                []Part
	IsTruncated          bool
	NextPartNumberMarker int
	MaxParts             int
}

ListPartsOutput contains the response from listing parts

type ListResponse added in v0.10.0

type ListResponse struct {
	// Name of the bucket
	Name string

	// Whether the results were truncated (more results available)
	IsTruncated bool

	// Token to get the next page of results (if truncated)
	NextContinuationToken string

	// List of objects in the bucket
	Objects []Object

	// Common prefixes when using delimiter (like directories)
	CommonPrefixes []string

	// Total number of keys returned
	KeyCount int64
}

ListResponse is returned by List.

type ListVersionsInput added in v0.11.0

type ListVersionsInput struct {
	// Required: The name of the bucket to list versions from
	Bucket string

	// Optional: A delimiter to group objects by (commonly "/")
	Delimiter string

	// Optional: Only list objects starting with this prefix
	Prefix string

	// Optional: Maximum number of objects to return
	MaxKeys int64

	// Optional: Key to start listing after (used for pagination)
	KeyMarker string

	// Optional: Version ID to start listing after (used for pagination)
	VersionIdMarker string
}

ListVersionsInput is passed to ListVersions as a parameter.

type ListVersionsResponse added in v0.11.0

type ListVersionsResponse struct {
	Name                string          `xml:"Name"`
	Prefix              string          `xml:"Prefix"`
	KeyMarker           string          `xml:"KeyMarker"`
	VersionIdMarker     string          `xml:"VersionIdMarker"`
	MaxKeys             int64           `xml:"MaxKeys"`
	Delimiter           string          `xml:"Delimiter"`
	IsTruncated         bool            `xml:"IsTruncated"`
	NextKeyMarker       string          `xml:"NextKeyMarker"`
	NextVersionIdMarker string          `xml:"NextVersionIdMarker"`
	Versions            []ObjectVersion `xml:"Version"`
	DeleteMarkers       []DeleteMarker  `xml:"DeleteMarker"`
	CommonPrefixes      []string
}

ListVersionsResponse is returned by ListVersions.

type MultipartUploadInput added in v0.11.0

type MultipartUploadInput struct {
	Bucket         string            // Required: bucket name
	ObjectKey      string            // Required: object key
	Body           io.Reader         // Required: file/data to upload
	ContentType    string            // Optional: content type
	CustomMetadata map[string]string // Optional: x-amz-meta-* headers
	ACL            string            // Optional: x-amz-acl
	PartSize       int64             // Optional: default 5MB, min 5MB
	MaxRetries     int               // Optional: default 3
	Concurrency    int               // Optional: default 1 (sequential)
	OnProgress     ProgressFunc      // Optional: progress callback

	// Optional: Server-side encryption (e.g. "AES256" or "aws:kms")
	ServerSideEncryption string
	// Optional: KMS Key ID (ARN or ID) when ServerSideEncryption is "aws:kms"
	SSEKMSKeyId string
}

MultipartUploadInput contains parameters for the high-level multipart upload

type MultipartUploadOutput added in v0.11.0

type MultipartUploadOutput struct {
	Location string
	Bucket   string
	Key      string
	ETag     string
	UploadID string
}

MultipartUploadOutput contains the response from a multipart upload

type Object added in v0.10.0

type Object struct {
	// Name of the object
	Key string

	// Size in bytes
	Size int64

	// When the object was last modified
	LastModified string

	// Entity tag of the object
	ETag string

	// Storage class (e.g., "STANDARD")
	StorageClass string
}

Object represents an S3 object in a bucket.

type ObjectVersion added in v0.11.0

type ObjectVersion struct {
	ETag         string `xml:"ETag"`
	IsLatest     bool   `xml:"IsLatest"`
	Key          string `xml:"Key"`
	LastModified string `xml:"LastModified"`
	Size         int64  `xml:"Size"`
	StorageClass string `xml:"StorageClass"`
	VersionId    string `xml:"VersionId"`
	Owner        struct {
		ID          string `xml:"ID"`
		DisplayName string `xml:"DisplayName"`
	} `xml:"Owner"`
}

ObjectVersion represents a version of an object.

type Owner added in v0.11.0

type Owner struct {
	ID          string `xml:"ID,omitempty"`
	DisplayName string `xml:"DisplayName,omitempty"`
}

Owner represents the owner of the bucket or object.

type Part added in v0.11.0

type Part struct {
	PartNumber   int
	ETag         string
	Size         int64
	LastModified time.Time
}

Part represents an uploaded part

type PolicyJSON

type PolicyJSON struct {
	Expiration string        `json:"expiration"`
	Conditions []interface{} `json:"conditions"`
}

PolicyJSON is policy rule.

type PresignedInput

type PresignedInput struct {
	Bucket                     string
	ObjectKey                  string
	Method                     string
	Timestamp                  time.Time
	ExtraHeaders               map[string]string
	ExpirySeconds              int
	ResponseContentDisposition string
}

PresignedInput is passed to GeneratePresignedURL as a parameter.

type PresignedMultipartInput added in v0.11.0

type PresignedMultipartInput struct {
	Bucket        string // Required: bucket name
	ObjectKey     string // Required: object key
	UploadID      string // Required: upload ID from InitiateMultipartUpload
	PartNumber    int    // Required: part number (1-10000)
	ExpirySeconds int    // Optional: default 3600
}

PresignedMultipartInput contains parameters for generating presigned multipart upload URLs

type ProgressFunc added in v0.11.0

type ProgressFunc func(info ProgressInfo)

ProgressFunc is called during upload with progress information

type ProgressInfo added in v0.11.0

type ProgressInfo struct {
	TotalBytes     int64 // Total bytes to upload (if known)
	UploadedBytes  int64 // Bytes uploaded so far
	CurrentPart    int   // Current part number
	TotalParts     int   // Total parts (if known)
	BytesPerSecond int64 // Current upload speed
}

ProgressInfo contains progress information for a multipart upload

type PutBucketAclInput added in v0.11.0

type PutBucketAclInput struct {
	// Required: The name of the bucket
	Bucket string

	// Optional: Canned ACL (private, public-read, public-read-write, authenticated-read)
	// If CannedACL is set, AccessControlPolicy is ignored.
	CannedACL string

	// Optional: Full Access Control Policy
	AccessControlPolicy *AccessControlPolicy
}

PutBucketAclInput is passed to PutBucketAcl.

type PutBucketLifecycleInput added in v0.11.0

type PutBucketLifecycleInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: The lifecycle configuration
	Configuration *LifecycleConfiguration
}

PutBucketLifecycleInput is passed to PutBucketLifecycle.

type PutBucketVersioningInput added in v0.11.0

type PutBucketVersioningInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: Versioning status (Enabled or Suspended)
	Status string

	// Optional: MFA Delete status (Enabled or Disabled)
	// Note: Requires MFA authentication in the request, which is not yet supported
	MfaDelete string
}

PutBucketVersioningInput is passed to PutBucketVersioning as a parameter.

type PutObjectAclInput added in v0.11.0

type PutObjectAclInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: The object key
	ObjectKey string

	// Optional: Version ID of the object
	VersionId string

	// Optional: Canned ACL (private, public-read, public-read-write, authenticated-read)
	// If CannedACL is set, AccessControlPolicy is ignored.
	CannedACL string

	// Optional: Full Access Control Policy
	AccessControlPolicy *AccessControlPolicy
}

PutObjectAclInput is passed to PutObjectAcl.

type PutObjectTaggingInput added in v0.11.0

type PutObjectTaggingInput struct {
	// Required: The name of the bucket
	Bucket string

	// Required: The object key
	ObjectKey string

	// Required: Tags to set on the object (max 10 tags)
	Tags map[string]string
}

PutObjectTaggingInput is passed to PutObjectTagging as a parameter.

type PutResponse added in v0.8.0

type PutResponse struct {
	ETag    string
	Headers http.Header
}

PutResponse is returned when the action is successful, and the service sends back an HTTP 200 response. The response returns ETag along with HTTP headers.

type S3

type S3 struct {
	AccessKey string
	SecretKey string
	Region    string
	Client    *http.Client

	Token     string
	Endpoint  string
	URIFormat string
	// contains filtered or unexported fields
}

S3 provides a wrapper around your S3 credentials.

func New

func New(region, accessKey, secretKey string) *S3

New returns an instance of S3.

func NewUsingIAM

func NewUsingIAM(region string) (*S3, error)

NewUsingIAM automatically generates an Instance of S3 using instance metatdata.

func (*S3) AbortMultipartUpload added in v0.11.0

func (s3 *S3) AbortMultipartUpload(input AbortMultipartUploadInput) error

AbortMultipartUpload aborts a multipart upload and cleans up parts

func (*S3) CompleteMultipartUpload added in v0.11.0

func (s3 *S3) CompleteMultipartUpload(input CompleteMultipartUploadInput) (CompleteMultipartUploadOutput, error)

CompleteMultipartUpload completes a multipart upload

func (*S3) CopyObject added in v0.11.0

func (s3 *S3) CopyObject(input CopyObjectInput) (CopyObjectOutput, error)

CopyObject copies an object from source to destination. Can copy within the same bucket or across buckets. This operation is server-side, avoiding download/upload cycle.

func (*S3) CreateBucket added in v0.11.0

func (s3 *S3) CreateBucket(input CreateBucketInput) (CreateBucketOutput, error)

CreateBucket creates a new S3 bucket. For regions other than us-east-1, it sends a LocationConstraint in the request body.

func (*S3) CreateUploadPolicies

func (s3 *S3) CreateUploadPolicies(uploadConfig UploadConfig) (UploadPolicies, error)

CreateUploadPolicies creates amazon s3 sigv4 compatible policy and signing keys with the signature returns the upload policy. https://docs.aws.amazon.com/ja_jp/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html

func (*S3) DeleteBucket added in v0.11.0

func (s3 *S3) DeleteBucket(input DeleteBucketInput) error

DeleteBucket deletes an empty S3 bucket. The bucket must be empty (no objects) before it can be deleted. Returns an error if the bucket is not empty or does not exist.

func (*S3) DeleteBucketLifecycle added in v0.11.0

func (s3 *S3) DeleteBucketLifecycle(input DeleteBucketInput) error

DeleteBucketLifecycle deletes the lifecycle configuration for a bucket.

func (*S3) DeleteObjectTagging added in v0.11.0

func (s3 *S3) DeleteObjectTagging(input DeleteObjectTaggingInput) error

DeleteObjectTagging removes all tags from an S3 object.

func (*S3) DeleteObjects added in v0.11.0

func (s3 *S3) DeleteObjects(input DeleteObjectsInput) (DeleteObjectsOutput, error)

DeleteObjects deletes multiple objects in a single request (max 1000). This is more efficient than calling FileDelete multiple times. Returns both successful deletions and errors.

func (*S3) FileDelete

func (s3 *S3) FileDelete(u DeleteInput) error

FileDelete makes a DELETE call with the file written as multipart and on successful upload, checks for 204 No Content.

func (*S3) FileDetails added in v0.7.0

func (s3 *S3) FileDetails(u DetailsInput) (DetailsResponse, error)

func (*S3) FileDownload added in v0.5.0

func (s3 *S3) FileDownload(u DownloadInput) (io.ReadCloser, error)

FileDownload makes a GET call and returns a io.ReadCloser. After reading the response body, ensure closing the response.

func (*S3) FilePut added in v0.8.0

func (s3 *S3) FilePut(u UploadInput) (PutResponse, error)

FilePut makes a PUT call to S3.

func (*S3) FileUpload

func (s3 *S3) FileUpload(u UploadInput) (UploadResponse, error)

FileUpload makes a POST call with the file written as multipart and on successful upload, checks for 200 OK.

func (*S3) FileUploadMultipart added in v0.11.0

func (s3 *S3) FileUploadMultipart(input MultipartUploadInput) (MultipartUploadOutput, error)

FileUploadMultipart handles the entire multipart upload workflow

func (*S3) GeneratePresignedURL

func (s3 *S3) GeneratePresignedURL(in PresignedInput) string

GeneratePresignedURL creates a Presigned URL that can be used for Authentication using Query Parameters. (https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html)

func (*S3) GeneratePresignedUploadPartURL added in v0.11.0

func (s3 *S3) GeneratePresignedUploadPartURL(in PresignedMultipartInput) string

GeneratePresignedUploadPartURL generates a presigned URL for uploading a specific part This enables browser-based multipart uploads where the frontend uploads parts directly to S3

func (*S3) GetBucketAcl added in v0.11.0

func (s3 *S3) GetBucketAcl(bucket string) (AccessControlPolicy, error)

GetBucketAcl gets the Access Control List (ACL) for a bucket.

func (*S3) GetBucketLifecycle added in v0.11.0

func (s3 *S3) GetBucketLifecycle(bucket string) (LifecycleConfiguration, error)

GetBucketLifecycle gets the lifecycle configuration for a bucket.

func (*S3) GetBucketVersioning added in v0.11.0

func (s3 *S3) GetBucketVersioning(bucket string) (GetBucketVersioningOutput, error)

GetBucketVersioning gets the versioning configuration for a bucket.

func (*S3) GetObjectAcl added in v0.11.0

func (s3 *S3) GetObjectAcl(input GetObjectAclInput) (AccessControlPolicy, error)

GetObjectAcl gets the Access Control List (ACL) for an object.

func (*S3) GetObjectTagging added in v0.11.0

func (s3 *S3) GetObjectTagging(input GetObjectTaggingInput) (GetObjectTaggingOutput, error)

GetObjectTagging retrieves the tags associated with an S3 object.

func (*S3) InitiateMultipartUpload added in v0.11.0

func (s3 *S3) InitiateMultipartUpload(input InitiateMultipartUploadInput) (InitiateMultipartUploadOutput, error)

InitiateMultipartUpload initiates a multipart upload and returns an upload ID

func (*S3) List added in v0.10.0

func (s3 *S3) List(input ListInput) (ListResponse, error)

List implements a simple S3 object listing API

func (*S3) ListAll added in v0.10.0

func (s3 *S3) ListAll(input ListInput) (iter.Seq[Object], func() error)

ListAll returns an iterator that yields all objects in the bucket, automatically handling pagination. It also returns a finish callback that should be called after iteration to check for any errors.

func (*S3) ListBuckets added in v0.11.0

func (s3 *S3) ListBuckets(input ListBucketsInput) (ListBucketsOutput, error)

ListBuckets lists all S3 buckets for the AWS account. It makes a GET request to the S3 service endpoint (not a specific bucket).

func (*S3) ListParts added in v0.11.0

func (s3 *S3) ListParts(input ListPartsInput) (ListPartsOutput, error)

ListParts lists the parts that have been uploaded for a multipart upload

func (*S3) ListVersions added in v0.11.0

func (s3 *S3) ListVersions(input ListVersionsInput) (ListVersionsResponse, error)

ListVersions lists object versions in a bucket.

func (*S3) PutBucketAcl added in v0.11.0

func (s3 *S3) PutBucketAcl(input PutBucketAclInput) error

PutBucketAcl sets the Access Control List (ACL) for a bucket. You can either use a CannedACL OR provide a full AccessControlPolicy.

func (*S3) PutBucketLifecycle added in v0.11.0

func (s3 *S3) PutBucketLifecycle(input PutBucketLifecycleInput) error

PutBucketLifecycle sets the lifecycle configuration for a bucket.

func (*S3) PutBucketVersioning added in v0.11.0

func (s3 *S3) PutBucketVersioning(input PutBucketVersioningInput) error

PutBucketVersioning sets the versioning configuration for a bucket.

func (*S3) PutObjectAcl added in v0.11.0

func (s3 *S3) PutObjectAcl(input PutObjectAclInput) error

PutObjectAcl sets the Access Control List (ACL) for an object. You can either use a CannedACL OR provide a full AccessControlPolicy.

func (*S3) PutObjectTagging added in v0.11.0

func (s3 *S3) PutObjectTagging(input PutObjectTaggingInput) error

PutObjectTagging sets tags on an existing S3 object. Replaces all existing tags with the provided tags. S3 allows up to 10 tags per object.

func (*S3) SetClient added in v0.3.0

func (s3 *S3) SetClient(client *http.Client) *S3

SetClient can be used to set the http client to be used by the package. If client passed is nil, http.DefaultClient is used.

func (*S3) SetEndpoint added in v0.5.0

func (s3 *S3) SetEndpoint(uri string) *S3

SetEndpoint can be used to the set a custom endpoint for using an alternate instance compatible with the s3 API. If no protocol is included in the URI, defaults to HTTPS.

func (*S3) SetIAMData added in v0.8.4

func (s3 *S3) SetIAMData(iamResp IAMResponse)

setIAMData sets the IAM data on the S3 instance.

func (*S3) SetToken added in v0.6.1

func (s3 *S3) SetToken(token string) *S3

SetToken can be used to set a Temporary Security Credential token obtained from using an IAM role or AWS STS.

func (*S3) UploadPart added in v0.11.0

func (s3 *S3) UploadPart(input UploadPartInput) (UploadPartOutput, error)

UploadPart uploads a single part for a multipart upload

type S3Error added in v0.10.0

type S3Error struct {
	XMLName   xml.Name `xml:"Error"`
	Code      string   `xml:"Code"`
	Message   string   `xml:"Message"`
	RequestID string   `xml:"RequestId"`
	HostID    string   `xml:"HostId"`
}

S3Error represents an S3 API error response

func (S3Error) Error added in v0.10.0

func (e S3Error) Error() string

Error returns a string representation of the S3Error

type Tag added in v0.11.0

type Tag struct {
	Key   string `xml:"Key"`
	Value string `xml:"Value"`
}

Tag represents a single S3 object tag with a key-value pair.

type UploadConfig

type UploadConfig struct {
	// Required
	BucketName         string
	ObjectKey          string
	ContentType        string
	ContentDisposition string
	ACL                string
	FileSize           int64
	// Optional
	UploadURL  string
	Expiration time.Duration
	MetaData   map[string]string
}

UploadConfig generate policies from config for POST requests to S3 using Signing V4.

type UploadInput

type UploadInput struct {
	// essential fields
	Bucket      string
	ObjectKey   string
	FileName    string
	ContentType string

	// optional fields
	ContentDisposition string
	ACL                string
	// Setting key/value pairs adds user-defined metadata
	// keys to the object, prefixed with AMZMetaPrefix.
	CustomMetadata map[string]string
	// Setting key/value pairs adds tags to the object (max 10 tags)
	Tags map[string]string

	// Server-side encryption (e.g. "AES256" or "aws:kms")
	ServerSideEncryption string
	// KMS Key ID (ARN or ID) when ServerSideEncryption is "aws:kms"
	SSEKMSKeyId string

	Body io.ReadSeeker
}

UploadInput is passed to FileUpload as a parameter.

type UploadPartInput added in v0.11.0

type UploadPartInput struct {
	Bucket     string    // Required: bucket name
	ObjectKey  string    // Required: object key
	UploadID   string    // Required: upload ID from InitiateMultipartUpload
	PartNumber int       // Required: part number (1-10000)
	Body       io.Reader // Required: part data
	Size       int64     // Required: size of part for Content-Length
}

UploadPartInput contains parameters for uploading a part

type UploadPartOutput added in v0.11.0

type UploadPartOutput struct {
	ETag       string // Required for CompleteMultipartUpload
	PartNumber int
}

UploadPartOutput contains the response from uploading a part

type UploadPolicies

type UploadPolicies struct {
	URL  string
	Form map[string]string
}

UploadPolicies Amazon s3 upload policies.

type UploadResponse added in v0.2.0

type UploadResponse struct {
	Location string `xml:"Location"`
	Bucket   string `xml:"Bucket"`
	Key      string `xml:"Key"`
	ETag     string `xml:"ETag"`
}

UploadResponse receives the following XML in case of success, since we set a 201 response from S3. Sample response:

<PostResponse>
  <Location>https://s3.amazonaws.com/link-to-the-file</Location>
  <Bucket>s3-bucket</Bucket>
  <Key>development/8614bd40-691b-4668-9241-3b342c6cf429/image.jpg</Key>
  <ETag>"32-bit-tag"</ETag>
</PostResponse>

type VersioningConfiguration added in v0.11.0

type VersioningConfiguration struct {
	Status    string `xml:"Status"`              // Enabled or Suspended
	MfaDelete string `xml:"MfaDelete,omitempty"` // Enabled or Disabled
}

VersioningConfiguration represents the versioning configuration of a bucket.

Jump to

Keyboard shortcuts

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