Range download with OSS SDK for Go 2.0
Range download allows you to download a specific byte range from an object instead of the entire file.
Usage notes
-
The sample code uses the China (Hangzhou) region ID
cn-hangzhouand a public endpoint. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about supported regions and endpoints, see Regions and Endpoints. -
In this topic, access credentials are obtained from environment variables. For more information, 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 policies or Bucket Policy.
|
API |
Action |
Description |
|
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 request context, which you can use to set the total timeout for the request. |
|
request |
*GetObjectRequest |
The request parameters. Set the Range parameter to specify the download range and the RangeBehavior parameter to enable standard range download behavior. For more information, see GetObjectRequest. |
|
optFns |
...func(*Options) |
Optional. Operation-level parameter overrides. For more information, see Options. |
Return values
|
Return value |
Type |
Description |
|
result |
*GetObjectResult |
The response of the API operation. Valid when err is nil. For more information, see GetObjectResult. |
|
err |
error |
The error message. Non-nil if the request fails. |
-
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 adds the RangeBehavior:standard request header to download a specified byte range with 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 complete sample code, see the GitHub example.
-
For the API reference, see GetObject.