Todos los productos
Search
Centro de documentos

Object Storage Service:Descarga por rangos (OSS SDK for Go 1.0)

Última actualización: Sep 22, 2026

En este tema se describe cómo usar la descarga por rangos para descargar un intervalo específico de datos de un objeto de manera eficiente.

Notas

  • 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 en la misma región que OSS, use 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 se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

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

  • Para ejecutar una descarga por rangos, debe contar con el permiso oss:GetObject. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

A continuación se muestra el código de ejemplo para descargar un rango específico de datos de un objeto.

package main

import (
	"io"
	"log"
	"strings"

	"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("Error: %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("Error: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	
	// Upload 1,000 bytes.
	strContent := ""
	for i := 0; i < 100; i++ {
		strContent += "abcdefghij"
	}
	log.Printf("content len: %d\n", len(strContent))

	// Upload a string.
	objectName := "yourObjectName"
	err = bucket.PutObject(objectName, strings.NewReader(strContent))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Query the data that is within the range from byte 15 to byte 35, which includes a total of 21 bytes. 
	// If the specified value range is invalid, the entire object is downloaded. For example, if the specified range includes a negative number or the specified value is greater than the object size, all content of the object is downloaded.
	body, err := bucket.GetObject(objectName, oss.Range(15, 35))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	defer body.Close()

	// Read the data and load it into the memory.
	data, err := io.ReadAll(body)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	log.Printf("data: %s", string(data))
}

Preguntas frecuentes

¿Qué sucede si se especifica un rango no válido para descargar datos?

Para un objeto de 1,000 bytes, el rango válido va del byte 0 al byte 999. Si el rango especificado no se encuentra entre el byte 0 y el byte 999, no surte efecto. En este caso, OSS devuelve el código de estado HTTP 200 y los datos completos del objeto. A continuación se muestran ejemplos de solicitudes no válidas y sus resultados:

  • Si establece Range: bytes en 500-2000, el valor final del rango no es válido. En este caso, OSS devuelve el código de estado HTTP 200 y los datos completos del objeto.

  • Si establece Range: bytes en 1000-2000, el valor inicial del rango no es válido. En este caso, OSS devuelve el código de estado HTTP 200 y los datos completos del objeto.

¿Cómo se especifican comportamientos estándar para descargar datos por rangos?

Si agrega x-oss-range-behavior:standard al encabezado de la solicitud, se modifica el comportamiento de descarga cuando el rango especificado no es válido. Por ejemplo, para un objeto de 1,000 bytes:

  • Si establece Range: bytes en 500-2000, el valor final del rango no es válido. En este caso, OSS devuelve el código de estado HTTP 206 y los datos comprendidos entre el byte 500 y el byte 999.

  • Si establece Range: bytes en 1000-2000, el valor inicial del rango no es válido. En este caso, OSS devuelve el código de estado HTTP 416 y el código de error InvalidRange.

El siguiente código de ejemplo muestra cómo especificar comportamientos estándar para descargar datos por rangos.

package main

import (
	"io"
	"log"
	"strings"

	"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("Error: %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("Error: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Upload 1,000 bytes. 
	strContent := ""
	for i := 0; i < 100; i++ {
		strContent += "abcdefghij"
	}
	log.Printf("content len: %d\n", len(strContent))

	// Upload the string. 
	objectName := "yourObjectName"
	err = bucket.PutObject(objectName, strings.NewReader(strContent))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// If you specify a range from byte 500 to byte 2000, the value at the end of the range is invalid. Then, OSS returns HTTP status code 206 and the data that is within the range from byte 500 to byte 999. 
	// If you specify a range from byte 1000 to byte 2000, the value at the start of the range is invalid. Then, OSS returns HTTP status code 416 and error code InvalidRange. 
	rangeStart := int64(1000)
	rangeEnd := int64(2000)
	body, err := bucket.GetObject(objectName, oss.Range(rangeStart, rangeEnd), oss.RangeBehavior("standard"))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	defer body.Close()

	// Read the data and load it into the memory.
	data, err := io.ReadAll(body)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	if len(data) != 500 {
		log.Fatalf("read data error, len: %d", len(data))
	}
	log.Printf("data: %s", string(data))
}

Referencias

  • Para consultar el código de ejemplo completo de descarga por rangos, visite GitHub.

  • Para obtener más información sobre la operación de API que permite ejecutar descargas por rangos, consulte GetObject.