Created
November 24, 2020 13:18
-
-
Save Markvandersteen/240df092b9bc9a9571bce0273c4c7a92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// EmptyBucket will empty a s4bucket. | |
func EmptyBucket(bucket string, s3Aws *s3.S3) error { | |
params := &s3.ListObjectsInput{ | |
Bucket: aws.String(bucket), | |
} | |
for { | |
//Requesting for batch of objects from s3 bucket | |
objects, err := s3Aws.ListObjects(params) | |
if err != nil { | |
return err | |
} | |
//Checks if the bucket is already empty | |
if len((*objects).Contents) == 0 { | |
return nil | |
} | |
//creating an array of pointers of ObjectIdentifier | |
objectsToDelete := make([]*s3.ObjectIdentifier, 0, 1000) | |
for _, object := range (*objects).Contents { | |
obj := s3.ObjectIdentifier{ | |
Key: object.Key, | |
} | |
objectsToDelete = append(objectsToDelete, &obj) | |
} | |
//Creating JSON payload for bulk delete | |
deleteArray := s3.Delete{Objects: objectsToDelete} | |
deleteParams := &s3.DeleteObjectsInput{ | |
Bucket: aws.String(bucket), | |
Delete: &deleteArray, | |
} | |
//Running the Bulk delete job (limit 1000) | |
_, err = s3Aws.DeleteObjects(deleteParams) | |
if err != nil { | |
return err | |
} | |
if *(*objects).IsTruncated { //if there are more objects in the bucket, IsTruncated = true | |
params.Marker = (*deleteParams).Delete.Objects[len((*deleteParams).Delete.Objects)-1].Key | |
} else { //if all objects in the bucket have been cleaned up. | |
break | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment