Todos os produtos
Search
Central de documentação

Object Storage Service:Listar objetos usando o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Liste todos os objetos em um bucket com o OSS SDK for Go.

Observações

Métodos

Operação de API avançada para listar objetos

Importante
  • O OSS SDK for Go V2 fornece um paginador que gerencia a paginação automática em várias chamadas de API.

  • O objeto paginador segue a convenção de nomenclatura <OperationName>Paginator, criado por New<OperationName>Paginator. Ele implementa os métodos HasNext e NextPage. O método HasNext verifica se há páginas restantes e o NextPage busca a próxima página.

Detalhes da 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 da solicitação

Parâmetro

Tipo

Descrição

request

*ListObjectsV2Request

Parâmetros da operação de API. ListObjectsV2Request

optFns

...func(*PaginatorOptions)

Opcional. Parâmetro no nível da operação. PaginatorOptions.

Parâmetros comuns do ListObjectsV2:

Parâmetro

Descrição

prefix

Prefixo obrigatório nos nomes dos objetos retornados.

maxKeys

Número máximo de objetos retornados por vez.

delimiter

Caractere usado para agrupar objetos por nome. Objetos com a mesma string entre o prefixo especificado e o primeiro delimitador são agrupados como um elemento CommonPrefixes.

startAfter

Posição inicial da operação de listagem.

fetchOwner

Indica se as informações do proprietário devem ser incluídas na resposta.

  • true: A resposta inclui as informações do proprietário.

  • false: A resposta não inclui as informações do proprietário.

Parâmetros de resposta

Parâmetro de resposta

Descrição

*ListObjectsV2Paginator

Objeto paginador que implementa os métodos HasNext e NextPage. HasNext verifica se há páginas restantes e NextPage busca a próxima página.

Operação de API básica para listar objetos

func (c *Client) ListObjectsV2(ctx context.Context, request *ListObjectsV2Request, optFns ...func(*Options)) (*ListObjectsV2Result, error)

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

ctx

context.Context

Contexto da solicitação. Permite definir a duração total da solicitação.

request

*ListObjectsV2Request

Parâmetros da operação de API. ListObjectsV2Request.

optFns

...func(*Options)

Opcional. Parâmetros no nível da operação. Options.

Parâmetros de resposta

Parâmetro de resposta

Tipo

Descrição

result

*ListObjectsV2Result

Resposta da operação, disponível quando err é nil. ListObjectsV2Result.

err

error

Status do erro. Diferente de nil se a solicitação falhar.

Código de exemplo

Listar objetos usando a operação de API avançada

Liste todos os objetos em um bucket usando o 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(&region, "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 usando a operação de API básica

Liste todos os objetos em um bucket chamando 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(&region, "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.")
}

Cenários comuns

Listar todos os objetos em um diretório

Usar o paginador

Lista todos os objetos em um diretório especificado usando o 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(&region, "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))
		}
	}
}

Usar ListObjectsV2

Lista todos os objetos em um diretório especificado usando o 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(&region, "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 cujos nomes contêm um prefixo especificado

Usar o paginador

Lista todos os objetos cujos nomes correspondem a um prefixo especificado.

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(&region, "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))
		}
	}
}

Usar ListObjectsV2

Lista todos os objetos cujos nomes correspondem a um prefixo especificado.

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(&region, "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 um número especificado de objetos

Usar o paginador

Lista um número específico de objetos usando o 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(&region, "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))
		}
	}
}

Usar ListObjectsV2

Lista um número específico de objetos usando o 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(&region, "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 os objetos a partir de uma posição específica

Usar o paginador

Lista objetos a partir de uma posição especificada usando o 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(&region, "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))
		}
	}
}

Usar ListObjectsV2

Lista objetos a partir de uma posição especificada usando o 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(&region, "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 os objetos no diretório raiz

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(&region, "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))
}

Referências