🚀 Get 25% off access to all my premium courses - use discount code FUNCMAIN at checkout - view the pricing page now!

Video:

Deleting Items from S3

March 19, 2018

Course Instructor: Elliot Forbes

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

Twitter: @Elliot_f

In this video, we are going to be looking at how we can implement a deleteItem function which will allow us to delete items from our S3 bucket and clean up after ourselves:

Deleting Items

Let’s set about implementing this deleteItem function now:

func deleteItem(sess *session.Session) {
	svc := s3.New(sess)
	input := &s3.DeleteObjectInput{
		Bucket: aws.String("go-aws-s3-course"),
		Key:    aws.String("my-file.txt"),
	}

	result, err := svc.DeleteObject(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			default:
				log.Fatal(aerr.Error())
			}
		} else {
			log.Fatal(err.Error())
		}
	}

	log.Printf("Result: %+v\n", result)

}

Let’s also update our main func:

func main() {
	fmt.Println("Downloads and Uploads")
	sess, err := session.NewSession(&aws.Config{
		Region: aws.String("us-west-2"),
	})
	if err != nil {
		log.Fatal("Could not get session")
	}
	uploadItem(sess)
	listItems(sess)

	deleteItem(sess)
	listItems(sess)
}

Perfect, with this in place, let’s try and run this and see if it deletes our file:

$ go run 04-deleting-items/main.go 
Downloads and Uploads
2021/03/14 12:52:00 Upload Result: &{Location:https://go-aws-s3-course.s3.us-west-2.amazonaws.com/my-file.txt VersionID:<nil> UploadID: ETag:0xc00047a240}
2021/03/14 12:52:00 Name: my-file.txt
2021/03/14 12:52:00 Size: 12
2021/03/14 12:52:00 Result: {

}