Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement par plage (OSS SDK for Go 1.0)

Dernière mise à jour :Sep 22, 2026

Cette rubrique explique comment télécharger efficacement une plage de données spécifique d'un objet en utilisant le téléchargement par plage.

Notes

  • Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.

  • Les identifiants d'accès utilisés dans cette rubrique proviennent des variables d'environnement. Pour savoir comment configurer vos identifiants d'accès, consultez Configurer les identifiants d'accès.

  • Cet exemple crée une instance OSSClient à l'aide d'un endpoint OSS. Pour d'autres configurations, comme l'utilisation d'un domaine personnalisé ou l'authentification via le Security Token Service (STS), consultez Configurer un client (Go SDK V1).

  • Le téléchargement par plage nécessite l'autorisation oss:GetObject. Pour plus d'informations, consultez Accorder une politique personnalisée.

Exemple de code

L'exemple de code suivant télécharge une plage de données spécifique d'un objet.

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

FAQ

Que se passe-t-il si je spécifie une plage invalide pour le téléchargement ?

Pour un objet de 1 000 octets, la plage valide s'étend de l'octet 0 à l'octet 999. Si la plage spécifiée est hors limites, elle est ignorée. OSS renvoie alors le code d'état HTTP 200 et l'intégralité de l'objet. Voici des exemples de requêtes invalides et leurs résultats :

  • Si vous définissez Range: bytes sur 500-2000, la valeur de fin est invalide. OSS renvoie le code d'état HTTP 200 et l'intégralité de l'objet.

  • Si vous définissez Range: bytes sur 1000-2000, la valeur de début est invalide. OSS renvoie le code d'état HTTP 200 et l'intégralité de l'objet.

Comment appliquer le comportement standard pour le téléchargement par plage ?

L'ajout de x-oss-range-behavior:standard à l'en-tête de la requête modifie le comportement lorsque la plage spécifiée est invalide. Pour un objet de 1 000 octets :

  • Si vous définissez Range: bytes sur 500-2000, la valeur de fin est invalide. OSS renvoie le code d'état HTTP 206 et les données comprises entre l'octet 500 et l'octet 999.

  • Si vous définissez Range: bytes sur 1000-2000, la valeur de début est invalide. OSS renvoie le code d'état HTTP 416 et le code d'erreur InvalidRange.

L'exemple de code suivant illustre l'utilisation du comportement standard pour le téléchargement par plage.

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

Références

  • Pour consulter l'exemple de code complet de téléchargement par plage, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API de téléchargement par plage, consultez GetObject.