From 1085f68f8a8cf75655e3a1ea0d45afd080d20a9e Mon Sep 17 00:00:00 2001 From: "daniel.naude" <danieln@bob.co.za> Date: Fri, 26 Jul 2024 09:30:12 +0200 Subject: [PATCH] Add ListObjectsInBucket function to S3 client The ListObjectsInBucket function allows listing all objects in an S3 bucket. This function retrieves the list of objects using the ListObjectsV2 API and returns an array of file names. --- s3/s3.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/s3/s3.go b/s3/s3.go index 631ba97..b036668 100644 --- a/s3/s3.go +++ b/s3/s3.go @@ -538,6 +538,29 @@ func (s ClientWithHelpers) DeleteObjectFromBucket(bucket string, fileName string return nil } +// ListObjectsInBucket - List all objects in an S3 bucket +func (s ClientWithHelpers) ListObjectsInBucket(bucket string) ([]string, error) { + if s.S3Client == nil { + return nil, ErrorS3ClientNotEstablished + } + + // list all the files in the bucket + listObjectsInput := &s3.ListObjectsV2Input{ + Bucket: aws.String(bucket), + } + listObjectsOutput, err := s.S3Client.ListObjectsV2(context.TODO(), listObjectsInput) + if err != nil { + return nil, err + } + + var fileNames []string + for _, object := range listObjectsOutput.Contents { + fileNames = append(fileNames, *object.Key) + } + + return fileNames, nil +} + func GetS3FileKey(fileName string, folder string) string { var fileKey string -- GitLab