Todos os produtos
Search
Central de documentação

Object Storage Service:Download por intervalo (OSS SDK for Go 1.0)

Última atualização: Sep 22, 2026

Este tópico descreve como usar o download por intervalo para baixar um intervalo específico de dados de um objeto de maneira eficiente.

Observações

  • Neste tópico, é utilizado o endpoint público da região China (Hangzhou). Se você quiser acessar o OSS a partir de outros services da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para mais informações sobre como configurar as credenciais de acesso, consulte Configure access credentials.

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

  • Para realizar o download por intervalo, você deve ter a permissão oss:GetObject. Para mais informações, consulte Grant a custom policy.

Código de exemplo

O código de exemplo a seguir é usado para baixar um intervalo específico 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 ao especificar um intervalo inválido para o download de dados?

Para um objeto com tamanho de 1.000 bytes, o intervalo válido vai do byte 0 ao byte 999. Se o intervalo especificado não estiver entre o byte 0 e o byte 999, o intervalo não terá efeito. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto. Os exemplos a seguir mostram requisições inválidas e os resultados retornados:

  • Caso você defina Range: bytes como 500-2000, o valor no final do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.

  • Caso você defina Range: bytes como 1000-2000, o valor no início do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 200 e os dados de todo o objeto.

Como especificar comportamentos padrão para baixar dados por intervalo?

Caso você especifique x-oss-range-behavior:standard no cabeçalho da requisição, o comportamento de download será modificado quando o intervalo definido não estiver dentro do intervalo válido. Para um objeto com tamanho de 1.000 bytes:

  • Caso você defina Range: bytes como 500-2000, o valor no final do intervalo será inválido. Nesse caso, o OSS retorna o código de status HTTP 206 e os dados que estão dentro do intervalo do byte 500 ao byte 999.

  • Caso você defina Range: bytes como 1000-2000, o valor no início do intervalo será inválido. Nesse caso, 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 baixar dados 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 o código de exemplo completo usado para realizar o download por intervalo, visite o GitHub.

  • Para mais informações sobre a operação de API que você pode chamar para realizar o download por intervalo, consulte GetObject.