Listez tous les objets d'un compartiment (bucket) avec OSS SDK for Go.
Notes
L'exemple de code utilise l'ID de région Chine (Hangzhou)
cn-hangzhouet le point de terminaison public. Pour accéder au compartiment depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Consultez Régions et points de terminaison OSS.Les identifiants d'accès sont obtenus à partir des variables d'environnement. Pour plus d'informations sur la configuration des identifiants d'accès, consultez la rubrique Configurer les identifiants d'accès.
La liste des objets nécessite l'autorisation
oss:ListObjects. Consultez la section Accorder des autorisations personnalisées aux utilisateurs RAM.
Méthodes
Opération API avancée pour la liste des objets
OSS SDK for Go V2 fournit un paginateur qui gère automatiquement la pagination sur plusieurs appels API.
L'objet paginateur suit la convention de nommage <OperationName>Paginator et est créé par New<OperationName>Paginator. Il implémente les méthodes HasNext et NextPage. La méthode HasNext vérifie s'il reste des pages et NextPage récupère la page suivante.
Détails de l'API :
type ListObjectsV2Paginator struct
func (p *ListObjectsV2Paginator) HasNext() bool
func (p *ListObjectsV2Paginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListObjectsV2Result, error)
func (c *Client) NewListObjectsV2Paginator(request *ListObjectsV2Request, optFns ...func(*PaginatorOptions)) *ListObjectsV2Paginator
Paramètres de requête
|
Paramètre |
Type |
Description |
|
request |
*ListObjectsV2Request |
Paramètres de l'opération API. ListObjectsV2Request |
|
optFns |
...func(*PaginatorOptions) |
Facultatif. Paramètre au niveau de l'opération. PaginatorOptions. |
Paramètres courants de ListObjectsV2 :
|
Paramètre |
Description |
|
prefix |
Le préfixe que les noms d'objets renvoyés doivent contenir. |
|
maxKeys |
Le nombre maximal d'objets renvoyés à chaque fois. |
|
delimiter |
Le caractère utilisé pour regrouper les objets par nom. Les objets ayant la même chaîne entre le préfixe spécifié et le premier délimiteur sont regroupés en tant qu'élément CommonPrefixes. |
|
startAfter |
La position à partir de laquelle l'opération de liste commence. |
|
fetchOwner |
Indique si les informations sur le propriétaire doivent être incluses dans la réponse.
|
Paramètres de réponse
|
Paramètre de réponse |
Description |
|
*ListObjectsV2Paginator |
L'objet paginateur qui implémente les méthodes HasNext et NextPage. HasNext vérifie s'il reste des pages et NextPage récupère la page suivante. |
Opération API de base pour la liste des objets
func (c *Client) ListObjectsV2(ctx context.Context, request *ListObjectsV2Request, optFns ...func(*Options)) (*ListObjectsV2Result, error)
Paramètres de requête
|
Paramètre |
Type |
Description |
|
ctx |
context.Context |
Le contexte de la requête. Permet de définir la durée totale de la requête. |
|
request |
*ListObjectsV2Request |
Paramètres de l'opération API. ListObjectsV2Request. |
|
optFns |
...func(*Options) |
Facultatif. Paramètres au niveau de l'opération. Options. |
Paramètres de réponse
|
Paramètre de réponse |
Type |
Description |
|
result |
*ListObjectsV2Result |
La réponse de l'opération, disponible lorsque err est nul. ListObjectsV2Result. |
|
err |
error |
Le statut d'erreur. Non nul si la requête échoue. |
Exemple de code
Lister les objets à l'aide de l'opération API avancée
Listez tous les objets d'un compartiment à l'aide du paginateur.
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to list objects.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
}
// Create a paginator.
p := client.NewListObjectsV2Paginator(request)
// Initialize the page number counter.
var i int
log.Println("Objects:")
// Traverse each page in the paginator.
for p.HasNext() {
i++
// Obtain the data on the next page.
page, err := p.NextPage(context.TODO())
if err != nil {
log.Fatalf("failed to get page %v, %v", i, err)
}
// Display information about each object on the page.
for _, obj := range page.Contents {
log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
}
}
}
Lister les objets à l'aide de l'opération API de base
Listez tous les objets d'un compartiment en appelant ListObjectsV2.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
flag.Parse() // Parse command line parameters.
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a ListObjectsV2 request.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
}
for {
// Perform the operation to list all objects.
lsRes, err := client.ListObjectsV2(context.TODO(), request)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display the results.
for _, object := range lsRes.Contents {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
*object.Key, *object.Type, object.Size, *object.ETag, object.LastModified.Format(time.RFC3339), *object.StorageClass)
}
// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
if lsRes.IsTruncated {
request.ContinuationToken = lsRes.NextContinuationToken
} else {
break // End the cycle if there are no more objects.
}
}
log.Println("All objects have been listed.")
}
Scénarios courants
Lister tous les objets d'un répertoire
Utiliser le paginateur
Liste tous les objets d'un répertoire spécifié à l'aide du paramètre Prefix.
package main
import (
"context"
"flag"
"fmt"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to list objects.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("exampledir/"), // List all objects in the specified directory
}
// Create a paginator.
p := client.NewListObjectsV2Paginator(request)
// Initialize the page number counter.
var i int
log.Println("Objects:")
// Traverse each page in the paginator.
for p.HasNext() {
i++
fmt.Printf("Page %v\n", i)
// Obtain the data on the next page.
page, err := p.NextPage(context.TODO())
if err != nil {
log.Fatalf("failed to get page %v, %v", i, err)
}
// Print the continuation token.
log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
// Display information about each object on the page.
for _, obj := range page.Contents {
log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
}
}
}
Utiliser ListObjectsV2
Liste tous les objets d'un répertoire spécifié à l'aide du paramètre Prefix.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
flag.Parse() // Parse command line parameters.
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a ListObjectsV2 request.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("exampledir/"), // List all objects in the specified directory.
}
for {
lsRes, err := client.ListObjectsV2(context.TODO(), request)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display the results.
for _, object := range lsRes.Contents {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
*object.Key, *object.Type, object.Size, *object.ETag, object.LastModified.Format(time.RFC3339), *object.StorageClass)
}
// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
if lsRes.IsTruncated {
request.ContinuationToken = lsRes.NextContinuationToken
} else {
break // End the cycle if there are no more objects.
}
}
log.Println("All objects have been listed.")
}
Lister les objets dont les noms contiennent un préfixe spécifié
Utiliser le paginateur
Liste tous les objets dont les noms correspondent à un préfixe spécifié.
package main
import (
"context"
"flag"
"fmt"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to list objects.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("my-object-"), // List all objects whose names contain the specified prefix.
}
// Create a paginator.
p := client.NewListObjectsV2Paginator(request)
// Initialize the page number counter.
var i int
log.Println("Objects:")
// Traverse each page in the paginator.
for p.HasNext() {
i++
fmt.Printf("Page %v\n", i)
// Obtain the data on the next page.
page, err := p.NextPage(context.TODO())
if err != nil {
log.Fatalf("failed to get page %v, %v", i, err)
}
// Print the continuation token.
log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
// Display information about each object on the page.
for _, obj := range page.Contents {
log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
}
}
}
Utiliser ListObjectsV2
Liste tous les objets dont les noms correspondent à un préfixe spécifié.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
flag.Parse() // Parse command line parameters.
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a ListObjectsV2 request.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Prefix: oss.Ptr("my-object-"),
}
for {
lsRes, err := client.ListObjectsV2(context.TODO(), request)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display the results.
for _, object := range lsRes.Contents {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
*object.Key, *object.Type, object.Size, *object.ETag, object.LastModified.Format(time.RFC3339), *object.StorageClass)
}
// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
if lsRes.IsTruncated {
request.ContinuationToken = lsRes.NextContinuationToken
} else {
break // End the cycle if there are no more objects.
}
}
log.Println("All objects have been listed.")
}
Lister un nombre spécifié d'objets
Utiliser le paginateur
Liste un nombre spécifié d'objets à l'aide du paramètre MaxKeys.
package main
import (
"context"
"flag"
"fmt"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to list objects.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
MaxKeys: 10, // The maximum number of objects returned each time.
}
// Create a paginator.
p := client.NewListObjectsV2Paginator(request)
// Initialize the page number counter.
var i int
log.Println("Objects:")
// Traverse each page in the paginator.
for p.HasNext() {
i++
fmt.Printf("Page %v\n", i)
// Obtain the data on the next page.
page, err := p.NextPage(context.TODO())
if err != nil {
log.Fatalf("failed to get page %v, %v", i, err)
}
// Print the continuation token.
log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
// Display information about each object on the page.
for _, obj := range page.Contents {
log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
}
}
}
Utiliser ListObjectsV2
Liste un nombre spécifié d'objets à l'aide du paramètre MaxKeys.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
flag.Parse() // Parse command line parameters.
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a ListObjectsV2 request.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
MaxKeys: 10, // The maximum number of objects returned each time.
}
for {
lsRes, err := client.ListObjectsV2(context.TODO(), request)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display the results.
for _, object := range lsRes.Contents {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
*object.Key, *object.Type, object.Size, *object.ETag, object.LastModified.Format(time.RFC3339), *object.StorageClass)
}
// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
if lsRes.IsTruncated {
request.ContinuationToken = lsRes.NextContinuationToken
} else {
break // End the cycle if there are no more objects.
}
}
log.Println("All objects have been listed.")
}
Lister tous les objets à partir d'une position spécifique
Utiliser le paginateur
Liste les objets à partir d'une position spécifiée à l'aide du paramètre StartAfter.
package main
import (
"context"
"flag"
"fmt"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to list objects.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
StartAfter: oss.Ptr("my-object"), // Specify the starting position for listing objects
}
// Create a paginator.
p := client.NewListObjectsV2Paginator(request)
// Initialize the page number counter.
var i int
log.Println("Objects:")
// Traverse each page in the paginator.
for p.HasNext() {
i++
fmt.Printf("Page %v\n", i)
// Obtain the data on the next page.
page, err := p.NextPage(context.TODO())
if err != nil {
log.Fatalf("failed to get page %v, %v", i, err)
}
// Print the continuation token.
log.Printf("ContinuationToken:%v\n", oss.ToString(page.ContinuationToken))
// Display information about each object on the page.
for _, obj := range page.Contents {
log.Printf("Object:%v, %v, %v\n", oss.ToString(obj.Key), obj.Size, oss.ToTime(obj.LastModified))
}
}
}
Utiliser ListObjectsV2
Liste les objets à partir d'une position spécifiée à l'aide du paramètre StartAfter.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Region in which the bucket is located.
bucketName string // Name of the bucket.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
flag.Parse() // Parse command line parameters.
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a ListObjectsV2 request.
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
StartAfter: oss.Ptr("my-object"), // Specify the starting position for listing objects.
}
for {
lsRes, err := client.ListObjectsV2(context.TODO(), request)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Display the results.
for _, object := range lsRes.Contents {
log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s\n",
*object.Key, *object.Type, object.Size, *object.ETag, object.LastModified.Format(time.RFC3339), *object.StorageClass)
}
// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
if lsRes.IsTruncated {
request.ContinuationToken = lsRes.NextContinuationToken
} else {
break // End the cycle if there are no more objects.
}
}
log.Println("All objects have been listed.")
}
Lister tous les objets du répertoire racine
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region.
bucketName string // The bucket name.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The `name` of the bucket.")
}
func main() {
flag.Parse() // Parse the command-line parameters.
// Check whether the bucket name is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Create a ListObjectsV2 request, and set the delimiter to a forward slash (/).
request := &oss.ListObjectsV2Request{
Bucket: oss.Ptr(bucketName),
Delimiter: oss.Ptr("/"), // Use forward slashes (/) as delimiters.
MaxKeys: 100, // The maximum number of objects returned per request.
}
// Variable to store all subdirectories (CommonPrefixes).
var subdirectories []oss.CommonPrefix
for {
lsRes, err := client.ListObjectsV2(context.TODO(), request)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
// Log and collect subdirectories (CommonPrefixes).
for _, prefix := range lsRes.CommonPrefixes {
log.Printf("Subdirectory: %v\n", *prefix.Prefix)
subdirectories = append(subdirectories, prefix)
}
// If there are more objects to list, update the value of the continueToken parameter to obtain the remaining results.
if lsRes.IsTruncated {
request.ContinuationToken = lsRes.NextContinuationToken
} else {
break // End the cycle if there are no more objects.
}
}
log.Println("All subdirectories have been listed.")
log.Printf("Total subdirectories: %d\n", len(subdirectories))
}
Références
Code d'exemple complet : GitHub.
Opération API avancée : NewListObjectsV2Paginator.
Opération API de base : ListObjectsV2.
Détails sur le paginateur : Guide du développeur.