Todos os produtos
Search
Central de documentação

Object Storage Service:List objects (OSS SDK for Go 1.0)

Última atualização: Sep 22, 2026

Este tópico descreve como listar objetos em um bucket com versionamento ativado. Isso inclui listar todos os objetos, objetos cujos nomes contêm um prefixo específico, bem como objetos e subdiretórios em um diretório específico.

Observações

  • Este tópico utiliza o endpoint público da região china (Hangzhou). Para acessar o oss a partir de outros service do Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do oss, consulte Regions and endpoints.

  • Este tópico utiliza variáveis de ambiente para obter as credenciais de acesso. Para mais informações sobre como configure credenciais de acesso, consulte Configure access credentials.

  • Este tópico demonstra como crie 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 Configure a client (Go SDK V1).

  • Para listar objetos, execute a operação e você precisa da permissão oss:ListObjectVersions. Para mais informações, consulte Grant a custom policy.

Cenários

A figura a seguir mostra os diretórios e os objetos em um bucket chamado examplebucket.

examplebucket
  └── fun
       └── exampleobject.jpg
       └── examplefile.txt
       └── destfolder
               └── image1.jpg
               └── image2.png
  └── srcfile.txt
  └── oss.jpg 

As seções a seguir descrevem como listar diferentes objetos ao especifique condições.

Para mais informações sobre os parâmetros que você pode configurar ao listar objetos, consulte ListObjectVersions (GetBucketVersions).

Código de exemplo

O código a seguir mostra como listar as versões de todos os objetos, incluindo marcadores de exclua, em um bucket 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// List the versions of all objects including delete markers in the bucket. 
	keyMarker := oss.KeyMarker("")
	versionIdMarker := oss.VersionIdMarker("")

	for {
		lor, err := bucket.ListObjectVersions(keyMarker, versionIdMarker)
		if err != nil {
			log.Fatalf("Failed to list object versions: %v", err)
		}

		// Display the version IDs of the objects. 
		for _, objVersion := range lor.ObjectVersions {
			log.Printf("Versionid: %s", objVersion.VersionId)
			log.Printf("Key: %s", objVersion.Key)
			log.Printf("Is Latest: %t", objVersion.IsLatest)
		}

		// Display the versions of the listed delete markers.
		for _, deleteMarker := range lor.ObjectDeleteMarkers {
			log.Printf("Delete Marker Versionid: %s", deleteMarker.VersionId)
			log.Printf("Delete Marker Key: %s", deleteMarker.Key)
		}

		// Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
		keyMarker = oss.KeyMarker(lor.NextKeyMarker)
		versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
		if !lor.IsTruncated {
			break
		}
	}
}

Resposta de exemplo:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true
Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
Key: fun/examplefile.txt
Is Latest true
Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
Key: fun/exampleobject.jpg
Is Latest true
Versionid: CAEQChiBgIDMgdbEthciIDUyMGI0NmZlNThkODQwY2ZhNmZhNTQ1Njk4ZTdj****
Key: oss.jpg
Is Latest true
Versionid: CAEQChiBgICIgdbEthciIDdlM2Q1YjYxZDIyZDQyMzI4MTRkNzVmYzdiMTBh****
Key: srcfile.txt
Is Latest true

Cenários comuns

Listar as versões de objetos cujos nomes contêm um prefixo específico

O código a seguir mostra como listar as versões de objetos cujos nomes contêm 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify the Prefix parameter to list the versions of objects whose names contain the fun prefix. 
	prefix := oss.Prefix("fun")
	keyMarker := oss.KeyMarker("")
	versionIdMarker := oss.VersionIdMarker("")

	for {
		lor, err := bucket.ListObjectVersions(prefix, keyMarker, versionIdMarker)
		if err != nil {
			log.Fatalf("Failed to list object versions: %v", err)
		}

		// Display the version IDs of the objects. 
		for _, objVersion := range lor.ObjectVersions {
			log.Printf("VersionId: %s", objVersion.VersionId)
			log.Printf("Key: %s", objVersion.Key)
			log.Printf("Is Latest: %t", objVersion.IsLatest)
		}

		// Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
		keyMarker = oss.KeyMarker(lor.NextKeyMarker)
		versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
		if !lor.IsTruncated {
			break
		}
	}
}

Resultados retornados:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true
Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
Key: fun/examplefile.txt
Is Latest true
Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
Key: fun/exampleobject.jpg
Is Latest true

Listar as versões de uma quantidade específica de objetos

O código a seguir mostra como listar as versões de uma quantidade específica 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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify the MaxKeys parameter to list up to four object versions in alphabetical order of the object names. 
	maxKeys := oss.MaxKeys(4)
	keyMarker := oss.KeyMarker("")
	versionIdMarker := oss.VersionIdMarker("")

	for {
		lor, err := bucket.ListObjectVersions(maxKeys, keyMarker, versionIdMarker)
		if err != nil {
			log.Fatalf("Failed to list object versions: %v", err)
		}

		// Display the version IDs of the objects. 
		for _, objVersion := range lor.ObjectVersions {
			log.Printf("Versionid: %s", objVersion.VersionId)
			log.Printf("Key: %s", objVersion.Key)
			log.Printf("Is Latest: %t", objVersion.IsLatest)
		}

		// Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
		keyMarker = oss.KeyMarker(lor.NextKeyMarker)
		versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
		if !lor.IsTruncated {
			break
		}
	}
}

Resposta de exemplo:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true

Listar as versões de todos os objetos por página

O código a seguir mostra como listar as versões de todos os objetos por página:

package main

import (
	"log"

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

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

	// Create an OSSClient instance. 
	// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
	// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// List the versions of all objects in the bucket by page. 
	keyMarker := oss.KeyMarker("")
	// Specify the MaxKeys parameter to list up to four object versions in alphabetical order of the object names. 
	maxKeys := oss.MaxKeys(4)
	versionIdMarker := oss.VersionIdMarker("")

	for {
		lor, err := bucket.ListObjectVersions(maxKeys, keyMarker, versionIdMarker)
		if err != nil {
			log.Fatalf("Failed to list object versions: %v", err)
		}

		// Display the version IDs of the objects. 
		for _, objVersion := range lor.ObjectVersions {
			log.Printf("Versionid: %s", objVersion.VersionId)
			log.Printf("Key: %s", objVersion.Key)
			log.Printf("Is Latest: %t", objVersion.IsLatest)
		}

		log.Println("---------------")

		// Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops. 
		if lor.IsTruncated {
			keyMarker = oss.KeyMarker(lor.NextKeyMarker)
			versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
		} else {
			break
		}
	}
}

Resposta de exemplo:

Versionid: CAEQChiBgIDHzNPEthciIDYzZGQ5M2VjOTU2ODRmMzA4ZWM4ODk0NjVmMWEx****
Key: fun/
Is Latest true
Versionid: CAEQChiBgID61tnEthciIDNmOGM2MTQ3ZjU1NTQ2MGFhYWJjNjQxMTQxZWZh****
Key: fun/destfolder/
Is Latest true
Versionid: CAEQChiBgMDczt3EthciIDEwYjliZmQ4MDNiMDQ2Njk4YWMxM2NhM2E5NzQ3****
Key: fun/destfolder/image1.jpg
Is Latest true
Versionid: CAEQChiBgIDszt3EthciIGU5OWU0ZTllMGY3NTRmMmU5NzVjZmJkYmE3ZWYy****
Key: fun/destfolder/image2.png
Is Latest true
---------------
Versionid: CAEQChiBgICditzEthciIDBiNTg1ZTZkMDRlMzRjNDdiMjRjMTBlOGUzMTM0****
Key: fun/examplefile.txt
Is Latest true
Versionid: CAEQChiBgMC.itzEthciIDEzNWVlYjNhYzNmMjQ4NWM5Nzc2NzllY2FiYmQ3****
Key: fun/exampleobject.jpg
Is Latest true
Versionid: CAEQChiBgIDMgdbEthciIDUyMGI0NmZlNThkODQwY2ZhNmZhNTQ1Njk4ZTdj****
Key: oss.jpg
Is Latest true
Versionid: CAEQChiBgICIgdbEthciIDdlM2Q1YjYxZDIyZDQyMzI4MTRkNzVmYzdiMTBh****
Key: srcfile.txt
Is Latest true
---------------

Referência

Para mais informações sobre a operação de API que lista as versões de todos os objetos em um bucket, consulte ListObjectVersions.