How to Use AWS S3 from Go
Use the official AWS SDK for Go v2 to interact with S3 by installing the module, configuring credentials via environment variables, and calling the PutObject or GetObject methods.
package main
import (
"context"
"fmt"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func main() {
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
panic(fmt.Sprintf("unable to load SDK config: %v", err))
}
client := s3.NewFromConfig(cfg)
// Example: Upload a file
_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(os.Getenv("AWS_S3_BUCKET")),
Key: aws.String("example.txt"),
Body: os.Stdin,
})
if err != nil {
panic(fmt.Sprintf("unable to put object: %v", err))
}
}
- Install the SDK:
go get github.com/aws/aws-sdk-go-v2/service/s3 - Set credentials:
export AWS_ACCESS_KEY_ID=your_keyandexport AWS_SECRET_ACCESS_KEY=your_secret - Run your Go program to execute the S3 operations.