Todos os produtos
Search
Central de documentação

Object Storage Service:Listar objetos (Go SDK V1)

Última atualização: Jul 03, 2026

Este tópico descreve como listar todos os objetos, objetos com um prefixo específico e objetos e subdiretórios em um diretório específico dentro de um bucket do Object Storage Service (OSS).

Observações

  • Neste tópico, é utilizado o endpoint público da região China (Hangzhou). Se você deseja acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do OSS, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • Para listar objetos, você deve ter a permissão oss:ListObjects. Para mais informações, consulte Conceder uma política personalizada.

  • O OSS SDK for Go 2.2.5 e versões posteriores suportam o retorno de informações RestoreInfo.

Informações de fundo

Você pode chamar a operação ListObjectsV2 ou ListObjects para listar até 1.000 objetos em um bucket por vez. Ao especificar diferentes parâmetros, você pode implementar diversos recursos de listagem, como listar todos os objetos após uma posição inicial especificada, listar objetos e subdiretórios em um diretório especificado e paginar os resultados da listagem. As principais diferenças entre essas duas operações são as seguintes:

  • Ao usar a operação ListObjectsV2, você deve usar o parâmetro fetchOwner para especificar se as informações de Owner dos objetos devem ser incluídas nos resultados.

  • Ao usar a operação ListObjects, as informações de Owner dos objetos são incluídas nos resultados por padrão.

    Nota

    Para buckets com versionamento habilitado, você deve usar a operação ListObjectsV2 para listar objetos.

As seções a seguir descrevem os parâmetros para listar objetos usando os métodos ListObjectsV2 e ListObjects.

ListObjectsV2

A tabela a seguir descreve os parâmetros para listar objetos usando o método ListObjectsV2.

Parâmetro

Descrição

prefix

O prefixo que os nomes dos objetos retornados devem conter.

delimiter

Um caractere para agrupar nomes de objetos. Todos os nomes de objetos que contêm a mesma string do prefixo até a primeira ocorrência do delimitador são agrupados como um único elemento (commonPrefixes).

startAfter

O ponto inicial para esta operação de listagem.

fetchOwner

Especifica se as informações de Owner devem ser incluídas nos resultados.

  • true: as informações de Owner são incluídas nos resultados.

  • false: as informações de Owner não são incluídas nos resultados.

Para mais informações, consulte ListObjectsV2.

ListObjects

A tabela a seguir descreve os parâmetros para listar objetos usando o método ListObjects.

Parâmetro

Descrição

delimiter

Um caractere para agrupar nomes de objetos. Todos os nomes de objetos que contêm a mesma string do prefixo até a primeira ocorrência do delimitador são agrupados como um único elemento (commonPrefixes).

prefix

O prefixo que os nomes dos objetos retornados devem conter.

maxKeys

O número máximo de objetos a serem retornados. O valor padrão é 100. O valor máximo é 1.000.

marker

O ponto inicial para esta operação de listagem.

Para mais informações, consulte ListObjects.

Exemplos

ListObjectsV2

O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar 100 objetos em um bucket.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// The initial continuation token.
	continueToken := ""

	for {
		// List all objects.
		lsRes, err := bucket.ListObjectsV2(oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		for _, object := range lsRes.Objects {
			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 more objects need to be listed, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

O código de exemplo a seguir mostra como usar o método ListObjects para listar 100 objetos em um bucket.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects.
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.Marker(marker))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		for _, object := range lsRes.Objects {
			log.Printf("Object Name: %s\n", object.Key)
		}

		// If more objects need to be listed, update the marker and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Cenários comuns

Listar um número específico de objetos

ListObjectsV2

O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar um número específico de objetos.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Set MaxKeys to specify the maximum number of objects to list, and then list the objects.
	maxKeys := 200
	continueToken := ""

	for {
		lsRes, err := bucket.ListObjectsV2(oss.MaxKeys(maxKeys), oss.StartAfter(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		for _, object := range lsRes.Objects {
			log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
				object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
		}

		// If more objects need to be listed, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.ContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

O código de exemplo a seguir mostra como usar o método ListObjects para listar um número específico de objetos.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Set the maximum number of objects to list, and then list the objects.
	maxKeys := 200
	lsRes, err := bucket.ListObjects(oss.MaxKeys(maxKeys))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects:\n", len(lsRes.Objects))
	for _, object := range lsRes.Objects {
		log.Printf("Object: %s\n", object.Key)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. NextMarker: %s\n", lsRes.NextMarker)
	} else {
		log.Println("All objects have been listed.")
	}
}

Listar objetos com um prefixo específico

ListObjectsV2

O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar objetos com um prefixo específico.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Set the Prefix parameter to list objects whose names start with my-object-.
	prefix := "my-object-"
	lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
			object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. Next Continuation Token: %s\n", lsRes.NextContinuationToken)
	} else {
		log.Println("All objects have been listed.")
	}
}

ListObjects

O código de exemplo a seguir mostra como usar o método ListObjects para listar objetos com um prefixo específico.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with the specified prefix. By default, 100 objects are listed.
	prefix := "my-object-"
	lsRes, err := bucket.ListObjects(oss.Prefix(prefix))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s\n", object.Key)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. Next Marker: %s\n", lsRes.NextMarker)
	} else {
		log.Println("All objects have been listed.")
	}
}

Listar objetos após um ponto inicial especificado

ListObjectsV2

Você pode definir o parâmetro StartAfter para especificar o ponto inicial da listagem. Todos os objetos que estão em ordem lexicográfica após o valor de StartAfter são retornados.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Specify to list objects after StartAfter. By default, 100 objects are listed.
	startAfter := "my-object-"
	lsRes, err := bucket.ListObjectsV2(oss.StartAfter(startAfter))
	if err != nil {
		log.Fatalf("Failed to list objects: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	log.Printf("Found %d objects starting after '%s':\n", len(lsRes.Objects), startAfter)
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s, Type: %s, Size: %d, ETag: %s, LastModified: %s, StorageClass: %s, Owner ID: %s, Owner DisplayName: %s\n",
			object.Key, object.Type, object.Size, object.ETag, object.LastModified.Format(time.RFC3339), object.StorageClass, object.Owner.ID, object.Owner.DisplayName)
	}

	if lsRes.IsTruncated {
		log.Printf("More objects available. Next Continuation Token: %s\n", lsRes.NextContinuationToken)
	} else {
		log.Println("All objects have been listed.")
	}
}

ListObjects

Você pode definir o parâmetro Marker para especificar o ponto inicial da listagem. Todos os objetos que estão em ordem lexicográfica após o valor de Marker são retornados.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Initialize the marker.
	marker := ""

	// Loop to list all objects.
	for {
		lsRes, err := bucket.ListObjects(oss.Marker(marker))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects:\n", len(lsRes.Objects))
		for _, object := range lsRes.Objects {
			log.Printf("Object: %s\n", object.Key)
		}

		// If the result is truncated, update the marker and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar todos os objetos por página

ListObjectsV2

Você pode usar o método ListObjectsV2 para listar todos os objetos em um bucket por página. Defina MaxKeys para especificar o número de objetos a serem listados em cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects by page. List 100 objects per page.
	continueToken := ""
	for {
		lsRes, err := bucket.ListObjectsV2(oss.MaxKeys(100), oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects:\n", len(lsRes.Objects))
		for _, object := range lsRes.Objects {
			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 the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

Você pode usar o método ListObjects para listar todos os objetos em um bucket por página. Defina MaxKeys para especificar o número de objetos a serem listados em cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List all objects by page. List 100 objects per page.
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.MaxKeys(100), oss.Marker(marker))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects:\n", len(lsRes.Objects))
		for _, object := range lsRes.Objects {
			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 the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar objetos com um prefixo específico por página

ListObjectsV2

Você pode usar o método ListObjectsV2 para listar objetos com um prefixo específico por página. Defina MaxKeys para especificar o número de objetos a serem listados em cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with a specific prefix by page. List 80 objects per page.
	prefix := "my-object-"
	continueToken := ""
	for {
		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.MaxKeys(80), oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
		for _, object := range lsRes.Objects {
			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 the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

Você pode usar o método ListObjects para listar objetos com um prefixo específico por página. Defina MaxKeys para especificar o número de objetos a serem listados em cada página.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with the specified prefix by page. List 80 objects per page.
	prefix := "my-object-"
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.MaxKeys(80), oss.Marker(marker), oss.Prefix(prefix))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results. By default, 100 records are returned at a time.
		log.Printf("Found %d objects with prefix '%s':\n", len(lsRes.Objects), prefix)
		for _, object := range lsRes.Objects {
			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 the result is truncated, update the marker and continue the loop.
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar informações sobre todos os objetos em um diretório específico

ListObjectsV2

Você pode usar o método ListObjectsV2 para listar informações sobre todos os objetos em um diretório específico (prefixo), incluindo o tamanho do objeto, a última modificação e o nome do objeto.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List objects with the specified prefix by page. By default, 100 records are returned at a time.
	continueToken := ""
	prefix := "fun"
	for {
		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, object := range lsRes.Objects {
			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 the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

ListObjects

Você pode usar o método ListObjects para listar informações sobre todos os objetos em um diretório específico (prefixo), incluindo o tamanho do objeto, a última modificação e o nome do objeto.

package main

import (
	"log"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Traverse the objects.
	marker := ""
	prefix := "test"
	for {
		lor, err := bucket.ListObjects(oss.Marker(marker), oss.Prefix(prefix))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, object := range lor.Objects {
			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 the result is truncated, update the marker and continue the loop.
		if lor.IsTruncated {
			marker = lor.NextMarker
		} else {
			break
		}
	}

	log.Println("All objects have been listed.")
}

Listar informações sobre todos os subdiretórios em um diretório específico

ListObjectsV2

O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar informações sobre todos os subdiretórios em um diretório específico (prefixo).

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List folders with the specified prefix by page. By default, 100 records are returned at a time.
	continueToken := ""
	prefix := ""
	for {
		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken), oss.Delimiter("/"))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, dirName := range lsRes.CommonPrefixes {
			log.Println("Directory Name:", dirName)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lsRes.IsTruncated {
			continueToken = lsRes.NextContinuationToken
		} else {
			break
		}
	}

	log.Println("All directories have been listed.")
}

ListObjects

O código de exemplo a seguir mostra como usar o método ListObjects para listar informações sobre todos os subdiretórios em um diretório específico (prefixo).

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// List folders with the specified prefix by page. By default, 100 records are returned at a time.
	marker := ""
	prefix := "yourDirPrefix" // Replace with the actual prefix.
	for {
		lor, err := bucket.ListObjects(oss.Marker(marker), oss.Prefix(prefix), oss.Delimiter("/"))
		if err != nil {
			log.Fatalf("Failed to list objects: %v", err)
		}

		// Print the results.
		for _, dirName := range lor.CommonPrefixes {
			log.Println("Directory Name:", dirName)
		}

		// If the result is truncated, update the continuation token and continue the loop.
		if lor.IsTruncated {
			marker = lor.NextMarker
		} else {
			break
		}
	}

	log.Println("All directories have been listed.")
}

Listar objetos e retornar informações de Owner

O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar objetos e retornar suas informações de Owner.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the bucket name.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Obtain Owner information and list the objects.
	lsRes, err := bucket.ListObjectsV2(oss.FetchOwner(true))
	if err != nil {
		log.Fatalf("Failed to list objects with owner information: %v", err)
	}

	// Print the results. By default, 100 records are returned at a time.
	for _, object := range lsRes.Objects {
		log.Printf("Object Key: %s, Owner ID: %s, Display Name: %s\n",
			object.Key, object.Owner.ID, object.Owner.DisplayName)
	}

	log.Println("All objects have been listed.")
}

Pastas

O OSS usa uma estrutura plana para armazenar objetos. Um diretório é um objeto de zero bytes cujo nome termina com uma barra (/). Você pode fazer upload e download desse objeto. Por padrão, um objeto cujo nome termina com uma barra (/) é exibido como um diretório no console do OSS. Para o código de exemplo completo usado para criar diretórios, visite o GitHub.

Você pode especificar os parâmetros delimiter e prefix para listar objetos por diretório.

  • Se você definir prefix como um nome de diretório na solicitação, os objetos e subdiretórios cujos nomes contêm o prefixo serão listados.

  • Se você especificar um prefixo e definir delimiter como uma barra (/) na solicitação, os objetos e subdiretórios cujos nomes começam com o prefixo especificado no diretório serão listados. Cada subdiretório é listado como um único elemento de resultado em CommonPrefixes. Os objetos e diretórios nesses subdiretórios não são listados.

Por exemplo, um bucket contém os seguintes objetos: oss.jpg, fun/test.jpg, fun/movie/001.avi e fun/movie/007.avi. A barra (/) é especificada como o delimitador de diretório. Os exemplos a seguir descrevem como listar objetos em diretórios simulados.

  • Listar todos os objetos em um bucket

    • ListObjectsV2

      O código de exemplo a seguir mostra como usar o ListObjectsV2 para listar todos os objetos em um bucket.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified bucket.
      	startAfter := ""
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.StartAfter(startAfter), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			startAfter = lsRes.StartAfter
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      

      ListObjects

      O código de exemplo a seguir mostra como usar o método ListObjects para listar todos os objetos em um bucket.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified bucket.
      	marker := ""
      	for {
      		lsRes, err := bucket.ListObjects(oss.Marker(marker))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      
    • O resultado a seguir é retornado quando você usa os dois métodos anteriores para listar todos os objetos no bucket.

      Objects:
      fun/movie/001.avi
      fun/movie/007.avi
      fun/test.jpg
      oss.jpg
      CommonPrefixes:  
  • Listar todos os objetos em um diretório específico

    • ListObjectsV2

      O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar todos os objetos em um diretório específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified directory.
      	prefix := "aaa/db-init"
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      

      ListObjects

      O código de exemplo a seguir mostra como usar o método ListObjects para listar todos os objetos em um diretório específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List all objects in the specified directory.
      	prefix := "aaa/db-init" // Replace with the actual prefix.
      	marker := ""
      	for {
      		lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed.")
      }
      
    • O resultado a seguir é retornado quando você usa os dois métodos anteriores para listar todos os objetos no diretório especificado.

      Objects:
      fun/movie/001.avi
      fun/movie/007.avi
      fun/test.jpg
      CommonPrefixes: 
  • Listar objetos e subdiretórios em um diretório

    • ListObjectsV2

      O código de exemplo a seguir mostra como usar o método ListObjectsV2 para listar objetos e subdiretórios em um diretório.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List objects and subdirectories in the specified directory.
      	prefix := "" // Set a prefix as needed.
      	delimiter := "/"
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.Delimiter(delimiter), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the results. By default, 100 records are returned at a time.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// Print the subdirectories.
      		for _, commonPrefix := range lsRes.CommonPrefixes {
      			log.Printf("Common Prefix: %s\n", commonPrefix)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects and subdirectories have been listed.")
      }
      

      ListObjects

      O código de exemplo a seguir mostra como usar o método ListObjects para listar objetos e subdiretórios em um diretório.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// List objects and subdirectories in the specified directory.
      	prefix := "aaa/db-init/" // Replace with the actual prefix.
      	marker := ""
      	delimiter := "/"
      	for {
      		lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker), oss.Delimiter(delimiter))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the list of objects.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s\n", object.Key)
      		}
      
      		// Print the list of subdirectories.
      		for _, commonPrefix := range lsRes.CommonPrefixes {
      			log.Printf("Common Prefix: %s\n", commonPrefix)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects and subdirectories have been listed.")
      }
      
    • O resultado a seguir é retornado quando você usa os dois métodos anteriores para listar objetos e subdiretórios no diretório especificado.

      Objects:
      fun/test.jpg
      
      CommonPrefixes:
      fun/movie/   
  • Obter o tamanho dos objetos em um diretório específico

    • ListObjectsV2

      O código de exemplo a seguir mostra como usar o método ListObjectsV2 para obter o tamanho dos objetos em um diretório específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Get the bucket.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// Get the size of objects in the specified directory.
      	prefix := "/fun" // Replace with the actual prefix.
      	continueToken := ""
      	for {
      		lsRes, err := bucket.ListObjectsV2(oss.Prefix(prefix), oss.ContinuationToken(continueToken))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the list of objects and their sizes.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			continueToken = lsRes.NextContinuationToken
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed with their sizes.")
      }
      

      ListObjects

      O código de exemplo a seguir mostra como usar o método ListObjects para obter o tamanho dos objetos em um diretório específico.

      package main
      
      import (
      	"log"
      
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      )
      
      func main() {
      	// Obtain access credentials from environment variables. Before you run this sample code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
      	if err != nil {
      		log.Fatalf("Failed to create credentials provider: %v", err)
      	}
      
      	// Create an OSSClient instance.
      	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
      	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
      	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider), oss.Region("yourRegion"), oss.AuthVersion(oss.AuthV4))
      	if err != nil {
      		log.Fatalf("Failed to create OSS client: %v", err)
      	}
      
      	// Specify the bucket name.
      	bucketName := "yourBucketName" // Replace with the actual bucket name.
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
      		log.Fatalf("Failed to get bucket: %v", err)
      	}
      
      	// Get the size of objects in the specified directory.
      	prefix := "test/" // Replace with the actual prefix.
      	marker := ""
      	for {
      		lsRes, err := bucket.ListObjects(oss.Prefix(prefix), oss.Marker(marker))
      		if err != nil {
      			log.Fatalf("Failed to list objects: %v", err)
      		}
      
      		// Print the list of objects and their sizes.
      		for _, object := range lsRes.Objects {
      			log.Printf("Object Key: %s, Size: %d Byte(s)\n", object.Key, object.Size)
      		}
      
      		// If the result is truncated, update the continuation token and continue the loop.
      		if lsRes.IsTruncated {
      			marker = lsRes.NextMarker
      		} else {
      			break
      		}
      	}
      
      	log.Println("All objects have been listed with their sizes.")
      }
      

Perguntas frequentes

Posso ordenar objetos pela última modificação ao listá-los?

Não. Para ordenar objetos pela última modificação, use a indexação de dados.

Referências

  • Para o código de exemplo completo de listagem de objetos, consulte o exemplo no GitHub.

  • Para mais informações sobre as operações de API para listagem de objetos, consulte ListObjectsV2 e ListObjects.