Todos los productos
Search
Centro de documentos

Object Storage Service:Listar buckets (OSS SDK for Go 1.0)

Última actualización: Sep 22, 2026

Un bucket es un contenedor para los objetos almacenados en Object Storage Service (OSS). Todos los objetos de OSS se almacenan dentro de buckets, los cuales se listan en orden alfabético. Puede listar los buckets que pertenecen a la cuenta actual de Alibaba Cloud en todas las regiones y que cumplen condiciones específicas.

Notas de uso

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Las credenciales de acceso de este ejemplo se obtienen de variables de entorno. Para conocer el procedimiento detallado de configuración de credenciales, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para listar buckets, se requiere el permiso oss:ListBuckets. Para obtener más información, consulte Grant a custom policy.

Ejemplos

A continuación se muestra un ejemplo de código para listar los buckets de todas las regiones dentro de la cuenta actual de 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
	}
}

Preguntas frecuentes

¿Cómo listo los buckets cuyo nombre contiene un prefijo específico?

Ejecute el siguiente código de ejemplo para listar, en todas las regiones de la cuenta actual de Alibaba Cloud, los buckets cuyo nombre contiene el prefijo example:

...
prefix := "example" // Specify the prefix.
lsRes, err := client.ListBuckets(oss.Prefix(prefix))
if err != nil {
	log.Fatalf("Failed to list buckets with prefix: %v", err)
}

log.Printf("Buckets with prefix '%s': %+v", prefix, lsRes.Buckets)
for _, bucket := range lsRes.Buckets {
	log.Printf("Bucket with prefix '%s': %s", prefix, bucket.Name)

}

¿Cómo listo los buckets cuyo nombre va después, en orden alfabético, del bucket indicado por el parámetro marker?

Ejecute el siguiente código de ejemplo para listar, en todas las regiones de la cuenta actual de Alibaba Cloud, los buckets cuyo nombre aparece después del bucket examplebucket en orden alfabético:

...
marker := "examplebucket" // Specify the marker parameter.
lsRes, err := client.ListBuckets(oss.Marker(marker))
if err != nil {
	log.Fatalf("Failed to list buckets with marker: %v", err)
}

log.Printf("Buckets with marker '%s': %+v", marker, lsRes.Buckets)
for _, bucket := range lsRes.Buckets {
	log.Printf("Bucket with marker '%s': %s", marker, bucket.Name)
}

¿Cómo limito la cantidad de buckets que se muestran en la lista?

Ejecute el siguiente código de ejemplo para listar todos los buckets de todas las regiones en la cuenta actual de Alibaba Cloud y establecer en 500 el número máximo de buckets devueltos:

...
maxKeys := 500
lsRes, err := client.ListBuckets(oss.MaxKeys(maxKeys))
if err != nil {
	log.Fatalf("Failed to list buckets with max keys: %v", err)
}

log.Printf("My buckets max num (%d): %+v", maxKeys, lsRes.Buckets)
for _, bucket := range lsRes.Buckets {
	log.Printf("Bucket with maxKeys (%d): %s", maxKeys, bucket.Name)
}

Referencias

  • Para consultar el código de ejemplo completo que lista buckets, visite GitHub.

  • Para obtener más información sobre la operación de API que permite listar buckets, consulte ListBuckets.