Skip to content

Instantly share code, notes, and snippets.

@bagasdisini
Created May 28, 2024 06:49
Show Gist options
  • Save bagasdisini/d03c8c2c54d475479f04e275a48929c2 to your computer and use it in GitHub Desktop.
Save bagasdisini/d03c8c2c54d475479f04e275a48929c2 to your computer and use it in GitHub Desktop.
Deleting file from AWS S3 using Go
func DeleteFromS3(dir string, filename string) error {
log.Debug("Deleting media from amazon s3 server...")
fileDestination := filename
if len(dir) > 0 {
fileDestination = dir + "/" + filename
}
svc := s3.New(session.Must(session.NewSession(&aws.Config{
Region: aws.String(config.S3.Region),
})))
input := &s3.DeleteObjectInput{
Bucket: aws.String(config.S3.Bucket),
Key: aws.String(fileDestination),
}
_, err := svc.DeleteObject(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case s3.ErrCodeNoSuchKey:
log.Error(fmt.Sprintf("No such key: %s", fileDestination))
default:
log.Error(fmt.Sprintf("Failed to delete object: %s", aerr.Error()))
}
} else {
log.Error(fmt.Sprintf("Failed to delete object: %s", err.Error()))
}
return err
}
// Optionally, you may want to confirm the deletion by waiting until the object is deleted
err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{
Bucket: aws.String(config.S3.Bucket),
Key: aws.String(fileDestination),
})
if err != nil {
log.Error(fmt.Sprintf("Error occurred while waiting for object to be deleted: %s", err.Error()))
return err
}
log.Debug("Successfully deleted media from amazon s3 server")
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment