Todos os produtos
Search
Central de documentação

Object Storage Service:Range download (OSS SDK for Go 1.0)

Última atualização: Jul 03, 2026

Este tópico descreve como usar o download por intervalo para baixar, de forma eficiente, uma faixa específica de dados de um objeto.

Observações

  • Este tópico utiliza 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, utilize 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 credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • Para baixar dados por intervalo, é necessária a permissão oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.

Código de exemplo

O código de exemplo a seguir baixa uma faixa específica de dados de um 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))
}

Perguntas frequentes

O que acontece se um intervalo inválido for especificado para o download?

Para um objeto com tamanho de 1.000 bytes, o intervalo válido vai do byte 0 ao byte 999. Caso o intervalo especificado esteja fora dessa faixa, ele não terá efeito. Nessa situação, o OSS retorna o código de status HTTP 200 e os dados completos do objeto. Os exemplos a seguir ilustram solicitações inválidas e seus respectivos resultados:

  • Ao definir Range: bytes como 500-2000, o valor final do intervalo é inválido. O OSS retorna o código de status HTTP 200 e todos os dados do objeto.

  • Ao definir Range: bytes como 1000-2000, o valor inicial do intervalo é inválido. O OSS retorna o código de status HTTP 200 e todos os dados do objeto.

Como especificar comportamentos padrão para download por intervalo?

Ao adicionar x-oss-range-behavior:standard ao cabeçalho da solicitação, o comportamento de download muda quando o intervalo especificado está fora da faixa válida. Para um objeto de 1.000 bytes:

  • Se Range: bytes for definido como 500-2000, o valor final é inválido. O OSS retorna o código de status HTTP 206 e os dados compreendidos entre o byte 500 e o byte 999.

  • Se Range: bytes for definido como 1000-2000, o valor inicial é inválido. O OSS retorna o código de status HTTP 416 e o código de erro InvalidRange.

O código de exemplo a seguir demonstra como especificar comportamentos padrão para download por intervalo.

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))
}

Referências

  • Para acessar o código de exemplo completo de download por intervalo, visite o GitHub.

  • Para mais informações sobre a operação de API usada no download por intervalo, consulte GetObject.