In this post we will review how to upload a file to AWS S3 in Go.
First we create an AWS session. We can use one of the methods specified in this post, but in this case we need to support different AWS session/credentials for each upload, hence we statically supply the AWS session configuration.
import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"strings"
)
func uploadFile() {
region := "us-east-1"
accessKey := "AKIAWXXXXXXXXXXXRQWU"
secretKey := "XXXXKsqJ2inJdxBdXXXXDE0jX+gxxFXXXXRVXX"
config := aws.Config{
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials(accessKey, secretKey, ""),
}
awsSession, err := session.NewSession(&config)
if err != nil {
panic(err)
}
Next we upload the file using S3 manager. The path in bucket can includes folders, and there is no need to create any sub folders, as the S3 does not actually keeps folders, instead it is a key-value implementation, and the folders are only used in the AWS console GUI presentation of the folders files.
bucketName := "my-bucket"
keyInBucket := "folder1/my-file.txt"
fileContent := "this is my data"
uploader := s3manager.NewUploader(awsSession)
input := &s3manager.UploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(keyInBucket),
Body: strings.NewReader(fileContent),
ContentType: aws.String("text/plain"),
}
_, err = uploader.UploadWithContext(context.Background(), input)
if err != nil {
panic(err)
}
}
No comments:
Post a Comment