This topic describes how to use range download to efficiently download a specific range of data from a file.
Usage notes
The sample code in this topic uses the China (Hangzhou) region ID,
cn-hangzhou. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud products in the same region, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints.In this topic, access credentials are read from environment variables. For more information about how to configure access credentials, see Configure access credentials.
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM Policy or Bucket Policy.
API | Action | Definition |
GetObject |
| Downloads an object. |
| When downloading an object, if you specify the object version through versionId, this permission is required. | |
| When downloading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, this permission is required. |
Method definition
func (c *Client) GetObject(ctx context.Context, request *GetObjectRequest, optFns ...func(*Options)) (*GetObjectResult, error)Request parameters
Parameter | Type | Description |
ctx | context.Context | The context of the request, which can be used to set the total timeout period of the request. |
request | *GetObjectRequest | The request parameters for a specific API operation. For example, you can set the Range parameter to specify the download range and the RangeBehavior parameter to specify the standard range download behavior. For more information, see GetObjectRequest. |
optFns | ...func(*Options) | Optional. The operation-level configuration parameters. For more information, see Options. |
Return values
Return value | Type | Description |
result | *GetObjectResult | The return value of the API operation. This parameter is valid when err is nil. For more information, see GetObjectResult. |
err | error | The status of the request. If the request fails, err is not nil. |
For a 1,000 byte object, the valid download range is from byte 0 to byte 999. If the specified range is invalid, the Range parameter has no effect. The response returns a 200 status code, and the entire object is transferred. The following examples describe invalid requests and their results:
If you set Range: bytes=500-2000, the end of the range is invalid. The entire file is returned, and the HTTP status code is 200.
If you set Range: bytes=1000-2000, the start of the range is invalid. The entire file is returned, and the HTTP status code is 200.
You can add the x-oss-range-behavior:standard request header to specify the standard range download behavior. This changes the download behavior of OSS for invalid ranges. For a 1,000 byte object:
If you set Range: bytes=500-2000, the end of the range is invalid. The data from byte 500 to byte 999 is returned, and the HTTP status code is 206.
If you set Range: bytes=1000-2000, the start of the range is invalid. An HTTP 416 status code and the InvalidRange error code are returned.
Sample code
The following sample code shows how to add the RangeBehavior:standard request header to download data from a specified range of a file using the standard download behavior.
package main
import (
"context"
"flag"
"io"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region.
bucketName string // The bucket name.
objectName string // The object name.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to get the object.
request := &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName), // The bucket name.
Key: oss.Ptr(objectName), // The object name.
Range: oss.Ptr("bytes=15-35"), // Specify the download range.
RangeBehavior: oss.Ptr("standard"), // Specify the standard range download behavior.
}
// Execute the operation to get the object and process the result.
result, err := client.GetObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get object %v", err)
}
defer result.Body.Close() // Make sure that the response body is closed when the function ends.
log.Printf("get object result:%#v\n", result)
// Read the content of the object.
data, _ := io.ReadAll(result.Body)
log.Printf("body:%s\n", data)
}
References
For the complete sample code for range download, see the GitHub example.
For more information about the API operation for range download, see GetObject.