Now that we’ve covered at a very high level what the S3 service does, let’s dive in and start writing code that will allow us to list the S3 buckets available to us!
Credential Management
Note - You will need to configure your aws credentials before this will work. You can find out more information on how to do that here: Configuration Basics
Let’s start off by creating a new main.go
file in which we’ll work:
package main
import "fmt"
func main() {
fmt.Println("Listing Buckets")
}
We’ll also want to ensure that we have go modules enabled within our project directory so that when we build or run our app, it can fetch the AWS SDK package.
$ go mod init github.com/TutorialEdge/go-aws-s3-course
I’ve done this at the root of my project directory so that I can reuse the modules through all of the videos.
Creating an S3 Client
Let’s start off by creating an S3 Client which will allow us to interact with the S3 service:
package main
import (
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
func main() {
fmt.Println("Listing Buckets")
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
log.Fatal(err.Error())
}
// Create S3 service client
svc := s3.New(sess)
}
With this in place, let’s now try and use this to list some of the buckets within our account:
result, err := svc.ListBuckets(nil)
if err != nil {
log.Fatalf("Unable to list buckets, %v", err)
}
fmt.Println("Buckets:")
for _, b := range result.Buckets {
fmt.Printf("* %s created on %s\n",
aws.StringValue(b.Name), aws.TimeValue(b.CreationDate))
}