Um bucket é um contêiner para objetos armazenados no Object Storage Service (OSS). Todos os objetos no OSS estão contidos em buckets. A listagem de buckets segue a ordem alfabética. Você pode listar buckets da conta atual do Alibaba Cloud, em todas as regiões, que atendam a condições específicas.
Observações de uso
Neste tópico, usamos 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.
Neste tópico, obtemos as credenciais de acesso a partir de variáveis de ambiente. Para mais informações sobre como configure credenciais de acesso, consulte Configure access credentials.
Este tópico demonstra como crie uma instância do 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 buckets, você precisa da permissão
oss:ListBuckets. Para mais informações, consulte Grant a custom policy.
Exemplos
O código de exemplo a seguir mostra como listar buckets em todas as regiões da conta atual do 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 vêm alfabeticamente após o bucket especificado pelo parâmetro marker?
Como listar um número específico de buckets?
Referências
Para acessar o código de exemplo completo para listar buckets, visite o GitHub.
Para mais informações sobre a operação de API que lista buckets, consulte ListBuckets.