Liste todos los objetos de un bucket con OSS SDK for Go.
Notas
El código de ejemplo utiliza el ID de región China (Hangzhou)
cn-hangzhouy el endpoint público. Para acceder al bucket desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. OSS regions and endpoints.Las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Para listar objetos se requiere el permiso
oss:ListObjects. Grant custom permissions to RAM users.
Métodos
Operación de API avanzada para listar objetos
OSS SDK for Go V2 proporciona un paginador que gestiona automáticamente la paginación en varias llamadas a la API.
El objeto paginador sigue la convención de nombres <OperationName>Paginator y se crea mediante New<OperationName>Paginator. Este implementa los métodos HasNext y NextPage. HasNext comprueba si quedan páginas pendientes y NextPage recupera la siguiente página.
Detalles de la 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
Parámetros de solicitud
|
Parámetro |
Tipo |
Descripción |
|
request |
*ListObjectsV2Request |
Parámetros de la operación de API. ListObjectsV2Request |
|
optFns |
...func(*PaginatorOptions) |
Opcional. Parámetro a nivel de operación. PaginatorOptions. |
Parámetros comunes de ListObjectsV2:
|
Parámetro |
Descripción |
|
prefix |
Prefijo que deben contener los nombres de los objetos devueltos. |
|
maxKeys |
Número máximo de objetos devueltos en cada llamada. |
|
delimiter |
Carácter utilizado para agrupar objetos por nombre. Los objetos que comparten la misma cadena entre el prefijo especificado y el primer delimitador se agrupan como un elemento CommonPrefixes. |
|
startAfter |
Posición a partir de la cual comienza la operación de listado. |
|
fetchOwner |
Indica si se incluye la información del propietario en la respuesta.
|
Parámetros de respuesta
|
Parámetro de respuesta |
Descripción |
|
*ListObjectsV2Paginator |
Objeto paginador que implementa los métodos HasNext y NextPage. HasNext comprueba si quedan páginas pendientes y NextPage recupera la siguiente página. |
Operación de API básica para listar objetos
func (c *Client) ListObjectsV2(ctx context.Context, request *ListObjectsV2Request, optFns ...func(*Options)) (*ListObjectsV2Result, error)
Parámetros de solicitud
|
Parámetro |
Tipo |
Descripción |
|
ctx |
context.Context |
Contexto de la solicitud. Permite establecer la duración total de la solicitud. |
|
request |
*ListObjectsV2Request |
Parámetros de la operación de API. ListObjectsV2Request. |
|
optFns |
...func(*Options) |
Opcional. Parámetros a nivel de operación. Options. |
Parámetros de respuesta
|
Parámetro de respuesta |
Tipo |
Descripción |
|
result |
*ListObjectsV2Result |
Respuesta de la operación, disponible cuando err es nil. ListObjectsV2Result. |
|
err |
error |
Estado de error. Distinto de nil si la solicitud falla. |
Código de ejemplo
Listar objetos mediante la operación de API avanzada
Liste todos los objetos de un bucket mediante el paginador.
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))
}
}
}
Listar objetos mediante la operación de API básica
Liste todos los objetos de un bucket al llamar a 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.")
}
Escenarios comunes
Listar todos los objetos de un directorio
Uso del paginador
Lista todos los objetos de un directorio específico mediante el parámetro 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))
}
}
}
Uso de ListObjectsV2
Lista todos los objetos de un directorio específico mediante el parámetro 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.")
}
Listar objetos cuyos nombres contienen un prefijo específico
Uso del paginador
Lista todos los objetos cuyos nombres coinciden con un prefijo determinado.
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))
}
}
}
Uso de ListObjectsV2
Lista todos los objetos cuyos nombres coinciden con un prefijo determinado.
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.")
}
Listar un número específico de objetos
Uso del paginador
Lista un número determinado de objetos mediante el parámetro 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))
}
}
}
Uso de ListObjectsV2
Lista un número determinado de objetos mediante el parámetro 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.")
}
Listar todos los objetos a partir de una posición específica
Uso del paginador
Lista objetos a partir de una posición indicada mediante el parámetro 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))
}
}
}
Uso de ListObjectsV2
Lista objetos a partir de una posición indicada mediante el parámetro 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.")
}
Listar todos los objetos del directorio raíz
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))
}
Referencias
Código de ejemplo completo: GitHub.
Operación de API avanzada: NewListObjectsV2Paginator.
Operación de API básica: ListObjectsV2.
Detalles del paginador: Guía para desarrolladores.