Reputation: 765
I'm trying to figure out how to upload an image/ file to a Wasabi Bucket using Golang. Amazon updated the S3 Golang client library to version 2 and I'm having a hard time piecing everything together how exactly how to use it.
Upvotes: 1
Views: 226
Reputation: 765
Alright, after a few hours of brutal trial and error, I finally figured it out. Hopefully this saves someone hours of work in the future!
const (
ACCESS_KEY = "access-key"
SECRET_KEY = "secret-key"
REGION = "ap-southeast-2"
ENDPOINT := "https://s3.ap-southeast-2.wasabisys.com"
)
func UploadImagesToWasabi() {
ctx := context.Background()
cfg, err := config.LoadDefaultConfig(ctx,
config.WithRegion(REGION),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(ACCESS_KEY, SECRET_KEY, "")),
config.WithEndpointResolverWithOptions(aws.EndpointResolverWithOptionsFunc(
func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: ENDPOINT,
}, nil
},
)),
)
if err != nil {
log.Fatal(err)
}
// Create an Amazon S3 service client
client := s3.NewFromConfig(cfg)
bucketName := "bucket-name"
objectKey := "preferrably-filename"
filePath := "path/to/file"
// Get the file
file, err := os.Open(filePath)
if err != nil {
log.Fatal("Unable to read file:", err)
return
}
// Upload the file to the Wasabi bucket
result, err := client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Body: file,
})
if err != nil {
log.Fatal("Unable to upload file:", err)
return
}
fmt.Printf("Successfully uploaded file: %v/n", result)
}
Make sure to set the correct endpoint for your bucket region otherwise you'll get this error: api error InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.
List of Wasabi Region Endpoints/ Service Urls
Feel free to suggest a cleaner/ more optimized way of writing this!
Upvotes: 1