In a versioning-enabled bucket, different versions of an object can have different storage classes. The RestoreObject operation restores the current version of an object by default. To restore a specific version, specify its version ID in the request.
Before you begin
The sample code uses the China (Hangzhou) region (
cn-hangzhou). The public endpoint is used by default. To access OSS from other Alibaba Cloud services in the same region, use the internal endpoint. For region-to-endpoint mappings, see Regions and endpoints.The sample code retrieves access credentials from environment variables. For other options, see Configure access credentials.
Restoring an object requires the
oss:RestoreObjectpermission. For details, see Attach a custom policy to a RAM user.
Sample code
The following code restores Archive, Cold Archive, or Deep Cold Archive objects:
package main
import (
"context"
"flag"
"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.
)
// Specify 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()
// Validate the bucket name.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Validate the region.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Validate the object name.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configuration and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Build the restore request.
request := &oss.RestoreObjectRequest{
Bucket: oss.Ptr(bucketName), // The bucket name.
Key: oss.Ptr(objectName), // The object name.
VersionId: oss.Ptr("yourVersionId"), // Specify the actual version ID.
RestoreRequest: &oss.RestoreRequest{
Days: 3, // Number of days the restored state is retained.
},
}
// Send the restore request.
result, err := client.RestoreObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to restore object %v", err)
}
// Print the restore result.
log.Printf("restore object result:%#v\n", result)
}References
For the complete sample code, see GitHub sample.
For RestoreObject API details, see RestoreObject.
For general information about restoring objects, see Restore objects.