1package main 2 3import ( 4 "context" 5 "flag" 6 "fmt" 7 "log" 8 9 "github.com/aws/aws-sdk-go-v2/config" 10 "github.com/aws/aws-sdk-go-v2/service/s3" 11) 12 13var ( 14 bucketName string 15 objectPrefix string 16 objectDelimiter string 17 maxKeys int 18) 19 20func init() { 21 flag.StringVar(&bucketName, "bucket", "", "The `name` of the S3 bucket to list objects from.") 22 flag.StringVar(&objectPrefix, "prefix", "", "The optional `object prefix` of the S3 Object keys to list.") 23 flag.StringVar(&objectDelimiter, "delimiter", "", 24 "The optional `object key delimiter` used by S3 List objects to group object keys.") 25 flag.IntVar(&maxKeys, "max-keys", 0, 26 "The maximum number of `keys per page` to retrieve at once.") 27} 28 29// Lists all objects in a bucket using pagination 30func main() { 31 flag.Parse() 32 if len(bucketName) == 0 { 33 flag.PrintDefaults() 34 log.Fatalf("invalid parameters, bucket name required") 35 } 36 37 // Load the SDK's configuration from environment and shared config, and 38 // create the client with this. 39 cfg, err := config.LoadDefaultConfig(context.TODO()) 40 if err != nil { 41 log.Fatalf("failed to load SDK configuration, %v", err) 42 } 43 44 client := s3.NewFromConfig(cfg) 45 46 // Set the parameters based on the CLI flag inputs. 47 params := &s3.ListObjectsV2Input{ 48 Bucket: &bucketName, 49 } 50 if len(objectPrefix) != 0 { 51 params.Prefix = &objectPrefix 52 } 53 if len(objectDelimiter) != 0 { 54 params.Delimiter = &objectDelimiter 55 } 56 57 // Create the Paginator for the ListObjectsV2 operation. 58 p := s3.NewListObjectsV2Paginator(client, params, func(o *s3.ListObjectsV2PaginatorOptions) { 59 if v := int32(maxKeys); v != 0 { 60 o.Limit = v 61 } 62 }) 63 64 // Iterate through the S3 object pages, printing each object returned. 65 var i int 66 log.Println("Objects:") 67 for p.HasMorePages() { 68 i++ 69 70 // Next Page takes a new context for each page retrieval. This is where 71 // you could add timeouts or deadlines. 72 page, err := p.NextPage(context.TODO()) 73 if err != nil { 74 log.Fatalf("failed to get page %v, %v", i, err) 75 } 76 77 // Log the objects found 78 for _, obj := range page.Contents { 79 fmt.Println("Object:", *obj.Key) 80 } 81 } 82} 83