### Go Example with AWS SDK v1 (Legacy) Source: https://github.com/johannesboyne/gofakes3/blob/master/README.md Demonstrates setting up a gofakes3 server and interacting with it using the legacy AWS SDK v1 for Go. It shows how to create a bucket and upload an object. This example requires the 'aws-sdk-go' package and configures a custom endpoint and region. ```golang // fake s3 backend := s3mem.New() faker := gofakes3.New(backend) ts := httptest.NewServer(faker.Server()) defers ts.Close() // configure S3 client s3Config := &aws.Config{ Credentials: credentials.NewStaticCredentials("YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", ""), Endpoint: aws.String(ts.URL), Region: aws.String("eu-central-1"), DisableSSL: aws.Bool(true), S3ForcePathStyle: aws.Bool(true), } newSession := session.New(s3Config) s3Client := s3.New(newSession) cparams := &s3.CreateBucketInput{ Bucket: aws.String("newbucket"), } // Create a new bucket using the CreateBucket call. _, err := s3Client.CreateBucket(cparams) if err != nil { // Message from an error. fmt.Println(err.Error()) return } // Upload a new object "testobject" with the string "Hello World!" to our "newbucket". _, err = s3Client.PutObject(&s3.PutObjectInput{ Body: strings.NewReader(`{"configuration": {"main_color": "#333"}, "screens": []}`), Bucket: aws.String("newbucket"), Key: aws.String("test.txt"), }) // ... accessing of test.txt through any S3 client would now be possible ``` -------------------------------- ### Run GoFakeS3 Standalone Server with Various Backends (CLI) Source: https://context7.com/johannesboyne/gofakes3/llms.txt Provides command-line examples for running GoFakeS3 as a standalone server with different backend storage options, including memory, BoltDB, filesystem, and direct filesystem. Options for auto-bucket creation, virtual-hosted style addressing, and disabling integrity checks are also shown. ```bash # Run with in-memory backend gofakes3 -backend memory -host :9000 -initialbucket my-bucket # Run with BoltDB backend for persistence gofakes3 -backend bolt -bolt.db ./s3data.db -host :9000 -initialbucket my-bucket # Run with filesystem backend (multiple buckets) gofakes3 -backend fs -fs.path /data/s3 -fs.meta /data/s3meta -fs.create -host :9000 # Run with direct filesystem (single bucket from existing directory) gofakes3 -backend directfs -directfs.path /var/data -directfs.bucket mybucket -host :9000 # Enable auto-bucket creation gofakes3 -backend memory -autobucket -host :9000 # Enable virtual-hosted style addressing gofakes3 -backend memory -hostbucket -host :9000 # Or with specific base domains gofakes3 -backend memory -hostbucketbase s3.localhost,s3.example.com -host :9000 # Disable integrity checks and enable permissive CORS gofakes3 -backend memory -no-integrity -insecure-cors -host :9000 # Quiet mode (suppress logging) gofakes3 -backend memory -quiet -host :9000 # Full example with all common options gofakes3 -backend bolt \ -bolt.db ./s3.db \ -host :9000 \ -initialbucket test-bucket \ -autobucket \ -insecure-cors \ 2>&1 | tee gofakes3.log ``` -------------------------------- ### Initialize GoFakeS3 Server with In-Memory Backend Source: https://context7.com/johannesboyne/gofakes3/llms.txt Creates a new GoFakeS3 server instance using an in-memory storage backend. This setup is ideal for ephemeral testing where data persistence is not required between server restarts. ```go package main import ( "net/http/httptest" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3mem" ) // Create in-memory backend backend := s3mem.New() // Create GoFakeS3 instance with options faker := gofakes3.New(backend, gofakes3.WithLogger(gofakes3.GlobalLog()), gofakes3.WithAutoBucket(true), // Auto-create buckets on first use gofakes3.WithIntegrityCheck(true), // Validate Content-MD5 ) // Start HTTP test server ts := httptest.NewServer(faker.Server()) defer ts.Close() ``` -------------------------------- ### Enable and Use Object Versioning with AWS SDK for Go Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates how to enable, get status, list, retrieve, and delete object versions for a bucket using the AWS SDK for Go. Requires the 'aws-sdk-go-v2/service/s3' package. ```go package main import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" ) // Enable versioning on a bucket _, err := client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{ Bucket: aws.String("my-bucket"), VersioningConfiguration: &types.VersioningConfiguration{ Status: types.BucketVersioningStatusEnabled, }, }) if err != nil { panic(err) } // Get versioning status verResp, _ := client.GetBucketVersioning(context.TODO(), &s3.GetBucketVersioningInput{ Bucket: aws.String("my-bucket"), }) fmt.Printf("Versioning status: %s\n", verResp.Status) // List object versions versionsResp, _ := client.ListObjectVersions(context.TODO(), &s3.ListObjectVersionsInput{ Bucket: aws.String("my-bucket"), Prefix: aws.String("config/"), }) for _, version := range versionsResp.Versions { fmt.Printf("Key: %s, VersionId: %s, IsLatest: %v\n", *version.Key, *version.VersionId, *version.IsLatest) } // Get specific object version getResp, _ := client.GetObject(context.TODO(), &s3.GetObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("config/settings.json"), VersionId: aws.String("version-id-here"), }) // Delete specific version _, _ = client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("config/settings.json"), VersionId: aws.String("version-id-here"), }) ``` -------------------------------- ### Configure GoFakeS3 Server Options Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates how to initialize a GoFakeS3 server with various configuration options, including logging, integrity checks, time skew limits, and CORS settings. ```go package main import ( "time" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3mem" ) backend := s3mem.New() faker := gofakes3.New(backend, gofakes3.WithGlobalLog(), gofakes3.WithAutoBucket(true), gofakes3.WithIntegrityCheck(true), gofakes3.WithTimeSkewLimit(15 * time.Minute), gofakes3.WithTimeSource(gofakes3.FixedTimeSource(time.Now())), gofakes3.WithMetadataSizeLimit(2048), gofakes3.WithHostBucket(true), gofakes3.WithHostBucketBase("s3.example.com", "s3.localhost"), gofakes3.WithoutVersioning(), gofakes3.WithInsecureCORS(), gofakes3.WithRequestID(1000), gofakes3.WithUnimplementedPageError(), ) handler := faker.Server() ``` -------------------------------- ### Initialize GoFakeS3 Server and AWS SDK v2 Client Source: https://github.com/johannesboyne/gofakes3/blob/master/README.md Demonstrates how to spin up an in-memory GoFakeS3 server using httptest and configure an AWS SDK v2 S3 client to communicate with the local mock server. ```golang backend := s3mem.New() faker := gofakes3.New(backend) ts := httptest.NewServer(faker.Server()) defer ts.Close() cfg, err := config.LoadDefaultConfig( context.TODO(), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("ACCESS_KEY", "SECRET_KEY", "")), config.WithHTTPClient(&http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, }), config.WithEndpointResolverWithOptions( aws.EndpointResolverWithOptionsFunc(func(_, _ string, _ ...interface{}) (aws.Endpoint, error) { return aws.Endpoint{URL: ts.URL}, nil }), ), ) client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = true }) ``` -------------------------------- ### Configure GoFakeS3 with Filesystem Backend Source: https://context7.com/johannesboyne/gofakes3/llms.txt Configures the GoFakeS3 server to serve files from the local filesystem. Supports both single-bucket and multi-bucket configurations using the Afero library. ```go package main import ( "log" "net/http" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3afero" "github.com/spf13/afero" ) // SingleBucket: Serve existing directory as a single S3 bucket baseFs := afero.NewBasePathFs(afero.NewOsFs(), "/path/to/data") metaFs := afero.NewMemMapFs() // Use memory for metadata backend, err := s3afero.SingleBucket("my-bucket", baseFs, metaFs) if err != nil { log.Fatal(err) } // Or MultiBucket: Support multiple buckets under a base path multiBaseFs := afero.NewBasePathFs(afero.NewOsFs(), "/path/to/s3data") multiBackend, err := s3afero.MultiBucket(multiBaseFs, s3afero.MultiWithMetaFs(afero.NewMemMapFs()), ) if err != nil { log.Fatal(err) } faker := gofakes3.New(backend) log.Fatal(http.ListenAndServe(":9000", faker.Server())) ``` -------------------------------- ### Perform Multipart Uploads with AWS SDK for Go Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates the lifecycle of a multipart upload, including initiation, uploading individual parts, and completing the process. This requires the AWS SDK for Go v2 and handles large file uploads by splitting them into smaller segments. ```go package main import ( "bytes" "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" ) // Initiate multipart upload createResp, err := client.CreateMultipartUpload(context.TODO(), &s3.CreateMultipartUploadInput{ Bucket: aws.String("my-bucket"), Key: aws.String("large-file.bin"), ContentType: aws.String("application/octet-stream"), }) if err != nil { panic(err) } uploadID := createResp.UploadId // Upload parts (minimum 5MB per part except last) var completedParts []types.CompletedPart partData := []byte("... part content ...") for partNum := 1; partNum <= 3; partNum++ { uploadResp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{ Bucket: aws.String("my-bucket"), Key: aws.String("large-file.bin"), UploadId: uploadID, PartNumber: aws.Int32(int32(partNum)), Body: bytes.NewReader(partData), }) if err != nil { panic(err) } completedParts = append(completedParts, types.CompletedPart{ ETag: uploadResp.ETag, PartNumber: aws.Int32(int32(partNum)), }) } // Complete multipart upload _, err = client.CompleteMultipartUpload(context.TODO(), &s3.CompleteMultipartUploadInput{ Bucket: aws.String("my-bucket"), Key: aws.String("large-file.bin"), UploadId: uploadID, MultipartUpload: &types.CompletedMultipartUpload{ Parts: completedParts, }, }) if err != nil { panic(err) } ``` -------------------------------- ### Configure S3 Addressing Styles Source: https://github.com/johannesboyne/gofakes3/blob/master/README.md Shows how to toggle between path-style and virtual-hosted style addressing when initializing the AWS SDK v2 S3 client. ```golang // Path-Style client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = true }) // Virtual-Hosted Style client := s3.NewFromConfig(cfg) ``` -------------------------------- ### List Objects with Prefix and Pagination in Go Source: https://context7.com/johannesboyne/gofakes3/llms.txt Lists objects in an S3 bucket using a prefix for filtering, a delimiter for directory-like grouping, and supports pagination for handling large result sets. Requires an initialized S3 client. ```go package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" ) // List objects with prefix (V2 API) listResp, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{ Bucket: aws.String("my-bucket"), Prefix: aws.String("config/"), Delimiter: aws.String("/"), MaxKeys: aws.Int32(100), }) if err != nil { panic(err) } // Print objects fmt.Printf("Found %d objects:\n", listResp.KeyCount) for _, obj := range listResp.Contents { fmt.Printf("- %s (size: %d bytes, modified: %s)\n", *obj.Key, *obj.Size, obj.LastModified) } // Print common prefixes (subdirectories) fmt.Println("Common prefixes (folders):") for _, prefix := range listResp.CommonPrefixes { fmt.Printf("- %s\n", *prefix.Prefix) } // Handle pagination if *listResp.IsTruncated { nextResp, _ := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{ Bucket: aws.String("my-bucket"), ContinuationToken: listResp.NextContinuationToken, }) // Process nextResp... } ``` -------------------------------- ### Listing Objects with Prefix and Pagination Source: https://context7.com/johannesboyne/gofakes3/llms.txt Lists objects in a bucket using prefix filtering, delimiters for directory-like navigation, and pagination for large result sets. ```APIDOC ## GET /my-bucket?prefix=config/&delimiter=/ ### Description Lists objects in a bucket, optionally filtering by a prefix and using a delimiter for hierarchical listing. Supports pagination. ### Method GET ### Endpoint /my-bucket ### Parameters #### Query Parameters - **prefix** (string) - Optional - Filters results to objects that begin with this prefix. - **delimiter** (string) - Optional - Causes keys that contain the delimiter to be rolled up into a single string. - **maxKeys** (integer) - Optional - Sets the maximum number of keys returned in the response. - **continuationToken** (string) - Optional - Used for paginating results. If present, the response will contain objects after the token. ### Response #### Success Response (200) - **KeyCount** (integer) - The number of keys in the response. - **Contents** (array of objects) - A list of objects matching the criteria. Each object contains: - **Key** (string) - The object's key. - **Size** (integer) - The object's size in bytes. - **LastModified** (string) - The last modified date and time of the object. - **CommonPrefixes** (array of objects) - A list of common prefixes (subdirectories) matching the criteria. Each object contains: - **Prefix** (string) - The common prefix. - **IsTruncated** (boolean) - Indicates if the listing is truncated (more results available). - **NextContinuationToken** (string) - The token to use for fetching the next page of results. #### Response Example ```json { "KeyCount": 2, "Contents": [ { "Key": "config/settings.json", "Size": 60, "LastModified": "2023-10-27T10:00:00Z" } ], "CommonPrefixes": [ { "Prefix": "config/subdir/" } ], "IsTruncated": false } ``` ``` -------------------------------- ### Connect AWS SDK v3 for JavaScript to GoFakeS3 Source: https://context7.com/johannesboyne/gofakes3/llms.txt Illustrates how to configure the AWS SDK v3 for JavaScript to connect to a GoFakeS3 server, including setting the custom endpoint, region, and credentials. Demonstrates common S3 operations like creating buckets, uploading, downloading, listing, and deleting objects within a Lambda handler. ```javascript import { S3Client, CreateBucketCommand, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3"; // Create S3 client with custom endpoint const s3Client = new S3Client({ region: "us-east-1", endpoint: "http://localhost:9000", forcePathStyle: true, // Required for GoFakeS3 credentials: { accessKeyId: "ACCESS_KEY", secretAccessKey: "SECRET_KEY", }, }); // Lambda handler example export const handler = async (event, context) => { try { // Create bucket await s3Client.send(new CreateBucketCommand({ Bucket: "my-bucket", })); // Upload object await s3Client.send(new PutObjectCommand({ Bucket: "my-bucket", Key: "data/config.json", Body: JSON.stringify({ setting: "value" }), ContentType: "application/json", })); // Download object const getResponse = await s3Client.send(new GetObjectCommand({ Bucket: "my-bucket", Key: "data/config.json", })); const content = await getResponse.Body.transformToString(); console.log("Content:", content); // List objects const listResponse = await s3Client.send(new ListObjectsV2Command({ Bucket: "my-bucket", Prefix: "data/", })); console.log("Objects:", listResponse.Contents); // Delete object await s3Client.send(new DeleteObjectCommand({ Bucket: "my-bucket", Key: "data/config.json", })); return { statusCode: 200, body: "Success" }; } catch (error) { console.error("Error:", error); throw error; } }; ``` -------------------------------- ### Uploading and Downloading Objects Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates how to upload objects to S3 with metadata support and download them back using the Gofakes3 API. ```APIDOC ## PUT /my-bucket/config/settings.json ### Description Uploads an object to a specified bucket with custom metadata. ### Method PUT ### Endpoint /my-bucket/config/settings.json ### Parameters #### Path Parameters - **my-bucket** (string) - Required - The name of the bucket. - **config/settings.json** (string) - Required - The key (path) of the object to upload. #### Request Body - **body** (string) - Required - The content of the object. - **ContentType** (string) - Optional - The content type of the object. - **Metadata** (map[string]string) - Optional - Custom metadata to associate with the object. ### Request Example ```json { "body": "{\"configuration\": {\"main_color\": \"#333\"}, \"screens\": []}", "ContentType": "application/json", "Metadata": { "custom-header": "my-value" } } ``` ## GET /my-bucket/config/settings.json ### Description Downloads an object from a specified bucket. ### Method GET ### Endpoint /my-bucket/config/settings.json ### Parameters #### Path Parameters - **my-bucket** (string) - Required - The name of the bucket. - **config/settings.json** (string) - Required - The key (path) of the object to download. ### Response #### Success Response (200) - **Body** (bytes) - The content of the downloaded object. - **ContentType** (string) - The content type of the object. - **ETag** (string) - The ETag of the object. #### Response Example ```json { "Body": "{\"configuration\": {\"main_color\": \"#333\"}, \"screens\": []}", "ContentType": "application/json", "ETag": "\"abcdef1234567890\"" } ``` ``` -------------------------------- ### Configure GoFakeS3 with BoltDB Backend Source: https://context7.com/johannesboyne/gofakes3/llms.txt Sets up a GoFakeS3 server using the BoltDB backend for persistent storage. This ensures that data remains available after the server process restarts. ```go package main import ( "log" "net/http" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3bolt" ) // Create BoltDB backend with persistent file storage backend, err := s3bolt.NewFile("./s3data.db", s3bolt.WithTimeSource(gofakes3.DefaultTimeSource()), ) if err != nil { log.Fatal(err) } // Create and configure GoFakeS3 faker := gofakes3.New(backend, gofakes3.WithLogger(gofakes3.GlobalLog()), ) // Start server on port 9000 log.Println("Starting GoFakeS3 server on :9000") log.Fatal(http.ListenAndServe(":9000", faker.Server())) ``` -------------------------------- ### Manage S3 Buckets with AWS SDK v2 Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates common bucket lifecycle operations including creation, existence checks, listing, and deletion using the AWS SDK v2 client connected to a GoFakeS3 server. ```go package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" ) // Create a new bucket _, err := client.CreateBucket(context.TODO(), &s3.CreateBucketInput{ Bucket: aws.String("my-test-bucket"), }) if err != nil { panic(err) } // Check if bucket exists (HEAD request) _, err = client.HeadBucket(context.TODO(), &s3.HeadBucketInput{ Bucket: aws.String("my-test-bucket"), }) if err != nil { fmt.Println("Bucket does not exist") } // List all buckets listResp, err := client.ListBuckets(context.TODO(), &s3.ListBucketsInput{}) if err != nil { panic(err) } for _, bucket := range listResp.Buckets { fmt.Printf("Bucket: %s, Created: %s\n", *bucket.Name, bucket.CreationDate) } // Delete bucket (must be empty) _, err = client.DeleteBucket(context.TODO(), &s3.DeleteBucketInput{ Bucket: aws.String("my-test-bucket"), }) if err != nil { panic(err) } ``` -------------------------------- ### Legacy Lambda Function with AWS SDK v2 for JavaScript Source: https://github.com/johannesboyne/gofakes3/blob/master/README.md Illustrates creating an S3 bucket using the legacy AWS SDK v2 for JavaScript in a Lambda handler. It uses the 'aws-sdk' package and requires manual configuration of the S3 endpoint and path style. The handler function takes event and context, and uses a callback to handle the response or errors. ```javascript var AWS = require("aws-sdk"); var ep = new AWS.Endpoint("http://localhost:9000"); var s3 = new AWS.S3({ endpoint: ep, s3ForcePathStyle: true, // Recommended for GoFakeS3 }); exports.handle = function (e, ctx) { s3.createBucket( { Bucket: "my-bucket", }, function (err, data) { if (err) return console.log(err, err.stack); ctx.succeed(data); }, ); }; ``` -------------------------------- ### Upload and Download Objects with Metadata in Go Source: https://context7.com/johannesboyne/gofakes3/llms.txt Uploads an object to S3 with custom metadata and content type, then downloads it back. It utilizes the AWS SDK for Go and demonstrates basic object manipulation. Requires an initialized S3 client. ```go package main import ( "bytes" "context" "io" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" ) // Upload an object with metadata objectContent := `{"configuration": {"main_color": "#333"}, "screens": []}` _, err := client.PutObject(context.TODO(), &s3.PutObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("config/settings.json"), Body: strings.NewReader(objectContent), ContentType: aws.String("application/json"), Metadata: map[string]string{ "custom-header": "my-value", }, }) if err != nil { panic(err) } // Download an object getResp, err := client.GetObject(context.TODO(), &s3.GetObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("config/settings.json"), }) if err != nil { panic(err) } def getResp.Body.Close() downloadedContent, err := io.ReadAll(getResp.Body) if err != nil { panic(err) } fmt.Printf("Content: %s\n", downloadedContent) fmt.Printf("Content-Type: %s\n", *getResp.ContentType) fmt.Printf("ETag: %s\n", *getResp.ETag) ``` -------------------------------- ### Implement Custom Backend Interface in Go Source: https://context7.com/johannesboyne/gofakes3/llms.txt Defines the Backend interface required to create custom storage backends for GoFakeS3. It also demonstrates how to return specific error types for missing resources or conflicts. ```go package main import ( "io" "github.com/johannesboyne/gofakes3" ) type Backend interface { ListBuckets() ([]gofakes3.BucketInfo, error) ListBucket(name string, prefix *gofakes3.Prefix, page gofakes3.ListBucketPage) (*gofakes3.ObjectList, error) CreateBucket(name string) error BucketExists(name string) (exists bool, err error) DeleteBucket(name string) error ForceDeleteBucket(name string) error GetObject(bucketName, objectName string, rangeRequest *gofakes3.ObjectRangeRequest) (*gofakes3.Object, error) HeadObject(bucketName, objectName string) (*gofakes3.Object, error) DeleteObject(bucketName, objectName string) (gofakes3.ObjectDeleteResult, error) PutObject(bucketName, key string, meta map[string]string, input io.Reader, size int64, conditions *gofakes3.PutConditions) (gofakes3.PutObjectResult, error) DeleteMulti(bucketName string, objects ...string) (gofakes3.MultiDeleteResult, error) CopyObject(srcBucket, srcKey, dstBucket, dstKey string, meta map[string]string) (gofakes3.CopyObjectResult, error) } func handleErrors() { err := gofakes3.BucketNotFound("bucket-name") err = gofakes3.KeyNotFound("object-key") err = gofakes3.ResourceError(gofakes3.ErrBucketAlreadyExists, "bucket-name") err = gofakes3.ResourceError(gofakes3.ErrBucketNotEmpty, "bucket-name") } ``` -------------------------------- ### Lambda Function with AWS SDK v3 for JavaScript Source: https://github.com/johannesboyne/gofakes3/blob/master/README.md Demonstrates creating an S3 bucket using AWS SDK v3 for JavaScript within a Lambda handler. It requires the '@aws-sdk/client-s3' package and configures a custom endpoint for gofakes3. The function takes event and context as input and returns the S3 response or throws an error. ```javascript // Using AWS SDK v3 for JavaScript import { S3Client, CreateBucketCommand } from "@aws-sdk/client-s3"; // Create an S3 client with custom endpoint const s3Client = new S3Client({ region: "us-east-1", endpoint: "http://localhost:9000", forcePathStyle: true, // Required for GoFakeS3 credentials: { accessKeyId: "ACCESS_KEY", secretAccessKey: "SECRET_KEY", }, }); // Lambda handler using async/await export const handler = async (event, context) => { try { const command = new CreateBucketCommand({ Bucket: "my-bucket", }); const response = await s3Client.send(command); return response; } catch (error) { console.error("Error:", error); throw error; } }; ``` -------------------------------- ### Configure AWS SDK v2 for GoFakeS3 Source: https://context7.com/johannesboyne/gofakes3/llms.txt Configures an AWS SDK v2 S3 client to communicate with a local GoFakeS3 instance. It requires enabling path-style addressing and custom endpoint resolution to point to the local server. ```go package main import ( "context" "crypto/tls" "net/http" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" ) // Configure AWS SDK v2 with custom endpoint cfg, err := config.LoadDefaultConfig( context.TODO(), config.WithCredentialsProvider( credentials.NewStaticCredentialsProvider("ACCESS_KEY", "SECRET_KEY", ""), ), config.WithHTTPClient(&http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, }), config.WithEndpointResolverWithOptions( aws.EndpointResolverWithOptionsFunc(func(_, _ string, _ ...interface{}) (aws.Endpoint, error) { return aws.Endpoint{URL: "http://localhost:9000"}, nil }), ), ) if err != nil { panic(err) } // Create S3 client with path-style addressing (required for GoFakeS3) client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.UsePathStyle = true }) ``` -------------------------------- ### Conditional S3 Put Operations with Go SDK Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates how to perform conditional `PutObject` operations in Go using the AWS SDK, leveraging `If-Match` and `If-None-Match` headers for atomic operations. This prevents race conditions by ensuring updates only occur if the object's ETag matches or if the object does not exist, respectively. ```go package main import ( "context" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" ) // First, create an object and get its ETag putResp, err := client.PutObject(context.TODO(), &s3.PutObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("counter.txt"), Body: strings.NewReader("1"), }) if err != nil { panic(err) } initialETag := *putResp.ETag // Conditional update: only if ETag matches (optimistic locking) _, err = client.PutObject(context.TODO(), &s3.PutObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("counter.txt"), Body: strings.NewReader("2"), IfMatch: aws.String(initialETag), // Only update if ETag matches }) if err != nil { // Will fail with PreconditionFailed if object was modified fmt.Println("Conditional update failed:", err) } // Conditional create: only if object doesn't exist _, err = client.PutObject(context.TODO(), &s3.PutObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("unique-key.txt"), Body: strings.NewReader("initial content"), IfNoneMatch: aws.String("*"), // Only create if key doesn't exist }) if err != nil { // Will fail with PreconditionFailed if object already exists fmt.Println("Object already exists:", err) } ``` -------------------------------- ### Delete Single and Multiple Objects in Go Source: https://context7.com/johannesboyne/gofakes3/llms.txt Demonstrates how to delete a single object from an S3 bucket and how to perform a bulk delete operation for multiple objects efficiently. Requires an initialized S3 client. ```go package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" ) // Delete a single object _, err := client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("config/settings.json"), }) if err != nil { panic(err) } // Delete multiple objects at once deleteResp, err := client.DeleteObjects(context.TODO(), &s3.DeleteObjectsInput{ Bucket: aws.String("my-bucket"), Delete: &types.Delete{ Objects: []types.ObjectIdentifier{ {Key: aws.String("file1.txt")}, {Key: aws.String("file2.txt")}, {Key: aws.String("folder/file3.txt")}, }, Quiet: aws.Bool(false), // Set to true to suppress success messages }, }) if err != nil { panic(err) } // Check for errors for _, deleted := range deleteResp.Deleted { fmt.Printf("Deleted: %s\n", *deleted.Key) } for _, errObj := range deleteResp.Errors { fmt.Printf("Failed to delete %s: %s\n", *errObj.Key, *errObj.Message) } ``` -------------------------------- ### HTML Form for Direct Browser Upload to GoFakeS3 Source: https://context7.com/johannesboyne/gofakes3/llms.txt Generates an HTML form that allows direct file uploads to a GoFakeS3 instance. This is useful for testing browser-based S3 upload workflows. It requires the `action` attribute to point to the GoFakeS3 endpoint and includes fields for the object key, ACL, metadata, and the file itself. ```html