In the last video, we looked at how we could retrieve and list all of the buckets within our AWS account. In this video, we’ll be looking at how we can create a bucket using the same approach by setting up a session and creating an S3 service instance.
This is the bucket we’ll be subsequently using for the rest of the videos within this course!
Implementation
Let’s dive into our main.go
file and start by creating a new session and S3 service instance:
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())
}
svc := s3.New(sess)
}
With this in place, we can then look at writing the code that will create the buckets for us:
svc := s3.New(session.New())
input := &s3.CreateBucketInput{
Bucket: aws.String("examplebucket"),
}
result, err := svc.CreateBucket(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case s3.ErrCodeBucketAlreadyExists:
fmt.Println(s3.ErrCodeBucketAlreadyExists, aerr.Error())
case s3.ErrCodeBucketAlreadyOwnedByYou:
fmt.Println(s3.ErrCodeBucketAlreadyOwnedByYou, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
Let’s navigate down into the terminal and try and run our new application:
$ go run 02-creating-buckets/main.go
Creating Buckets
2021/03/13 14:01:37 {
Location: "http://go-aws-s3-course.s3.amazonaws.com/"
}
Pefect, we now have a bucket created for us by the AWS SDK and we can now start to play around with that bucket in the next videos within this course!