Um bucket é um contêiner para objetos armazenados no Object Storage Service (OSS). Todos os objetos no OSS residem em buckets, listados em ordem alfabética. Você pode listar os buckets da conta atual da Alibaba Cloud em todas as regiões que atendam a condições específicas.
Observações de uso
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
As credenciais de acesso neste exemplo são obtidas de variáveis de ambiente. Para saber como configurar essas credenciais, consulte Configurar credenciais de acesso.
Este exemplo demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
Para listar buckets, você precisa da permissão
oss:ListBuckets. Para mais informações, consulte Conceder uma política personalizada.
Exemplos
O código de exemplo a seguir mostra como listar buckets em todas as regiões da conta atual da Alibaba Cloud:
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)
}
// List all buckets in all regions within the current Alibaba Cloud account.
marker := ""
for {
lsRes, err := client.ListBuckets(oss.Marker(marker))
if err != nil {
log.Fatalf("Failed to list buckets: %v", err)
}
// By default, a maximum of 100 buckets are listed at a time.
for _, bucket := range lsRes.Buckets {
log.Printf("Bucket: %s", bucket.Name)
}
if !lsRes.IsTruncated {
break
}
marker = lsRes.NextMarker
}
}
Perguntas frequentes
Como listar buckets cujos nomes contêm um prefixo específico?
Como listar buckets cujos nomes aparecem alfabeticamente após o bucket especificado pelo parâmetro marker?
Como listar um número específico de buckets?
Referências
Para obter o código de exemplo completo sobre como listar buckets, acesse o GitHub.
Para mais informações sobre a operação de API usada para listar buckets, consulte ListBuckets.