Copy objects using OSS SDK for Go 2.0

Updated at:

This topic describes how to copy objects in a versioning-enabled bucket. You can call the CopyObject operation to copy an object up to 1 GB in size and call the UploadPartCopy operation to copy an object larger than 1 GB in size.

Usage notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • To copy objects, you must have the oss:GetObject and oss:PutObject permissions. For more information, see Grant custom permissions to RAM users.

Sample code

Copy objects

Note

You can call CopyObject to copy an object that is up to 1 GB in size from a source bucket to a destination bucket within the same region.

  • If you do not specify a version ID in the x-oss-copy-source header of the CopyObject request, the current version of the object is copied. If the current version of the object is a delete marker, OSS returns HTTP status code 404, which indicates that the object does not exist. You can specify a version ID in the x-oss-copy-source header to copy the specified version. Delete markers cannot be copied.

  • You can copy a previous version of an object to the same bucket. The copied previous version becomes the current version of the object. This way, the previous version of the object is recovered as the latest version.

  • If versioning is enabled for the destination bucket, OSS generates a unique version ID for the destination object. The version ID is returned in the response as the x-oss-version-id header value. If versioning is disabled or suspended for the destination bucket, OSS generates a version whose version ID is null for the destination object and overwrites the original version whose version ID is null.

  • Appendable objects cannot be copied to a destination bucket for which versioning is enabled or suspended.

The following sample code provides an example of how to copy 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 // Region in which the object is stored.
	srcBucketName  string // Name of the source bucket.
	srcObjectName  string // Name of the source object.
	destBucketName string // Name of the destination bucket.
	destObjectName string // Name of the destination object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&srcBucketName, "src-bucket", "", "The name of the source bucket.")
	flag.StringVar(&srcObjectName, "src-object", "", "The name of the source object.")
	flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
	flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the source bucket is specified.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// If the name of the destination bucket is not specified, the name of the source bucket will be used.
	if len(destBucketName) == 0 {
		destBucketName = srcBucketName
	}

	// Check whether the name of the source object is specified.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the name of the destination object is specified.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a copy request.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:           oss.Ptr(destBucketName),            // Name of the destination bucket.
		Key:              oss.Ptr(destObjectName),            // Name of the destination object.
		SourceKey:        oss.Ptr(srcObjectName),             // Name of the source object.
		SourceBucket:     oss.Ptr(srcBucketName),             // Name of the source bucket.
		SourceVersionId:  oss.Ptr("yourVersionId"),           // Specify the actual version ID of the source object.
		StorageClass:     oss.StorageClassStandard,           // Set the storage class to Standard.
		TaggingDirective: oss.Ptr("Replace"),                 // Tags of the source object are not copied.
		Tagging:          oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual tags of the destination object.
	}

	// Perform the operation and process the result.
	copyResult, err := client.CopyObject(context.TODO(), copyRequest)
	if err != nil {
		log.Fatalf("failed to copy object: %v", err)
	}

	// Display the result.
	log.Printf("copy object result versionId:%#v\n", *copyResult.VersionId)

}

Multipart copy

Note

To copy an object larger than 1 GB, you must split the object into parts and copy them sequentially by calling UploadPartCopy.

  • By default, UploadPartCopy uploads a part by copying data from the current version of an object. You can specify the SourceVersionId parameter in the UploadPartCopyRequest as the condition to upload a part by copying data from a specified version of an existing object.

  • If no version ID is specified in the request and the current version of the source object is a delete marker, OSS returns 404 Not Found. If versionId is specified in the request and the specified version of the source object is a delete marker, OSS returns 400 Bad Request.

The following sample code provides an example of multipart copy.

package main

import (
	"context"
	"flag"
	"log"
	"sync"

	"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 // Region in which the object is stored.
	srcBucketName  string // Name of the source bucket.
	srcObjectName  string // Name of the source object.
	destBucketName string // Name of the destination bucket.
	destObjectName string // Name of the destination object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&srcBucketName, "src-bucket", "", "The name of the source bucket.")
	flag.StringVar(&srcObjectName, "src-object", "", "The name of the source object.")
	flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
	flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Specify the upload ID.
	var uploadId string

	// Check whether the name of the source bucket is specified.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// If the name of the destination bucket is not specified, the name of the source bucket will be used.
	if len(destBucketName) == 0 {
		destBucketName = srcBucketName
	}

	// Check whether the name of the source object is specified.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the name of the destination object is specified.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Initiate multipart upload.
	initRequest := &oss.InitiateMultipartUploadRequest{
		Bucket: oss.Ptr(destBucketName),
		Key:    oss.Ptr(destObjectName),
	}
	initResult, err := client.InitiateMultipartUpload(context.TODO(), initRequest)
	if err != nil {
		log.Fatalf("failed to initiate multipart upload %v", err)
	}

	// Display the result.
	log.Printf("initiate multipart upload result:%#v\n", *initResult.UploadId)
	uploadId = *initResult.UploadId

	// Initialize a wait group and a mutex.
	var wg sync.WaitGroup
	var parts []oss.UploadPart
	count := 3
	var mu sync.Mutex

	// Launch multiple goroutines to perform multipart upload.
	for i := 0; i < count; i++ {
		wg.Add(1)
		go func(partNumber int, i int) {
			defer wg.Done()

			// Create a multipart upload request.
			partRequest := &oss.UploadPartCopyRequest{
				Bucket:          oss.Ptr(destBucketName),  // Name of the destination bucket.
				Key:             oss.Ptr(destObjectName),  // Name of the destination object.
				SourceBucket:    oss.Ptr(srcBucketName),   // Name of the source bucket.
				SourceKey:       oss.Ptr(srcObjectName),   // Name of the source object.
				SourceVersionId: oss.Ptr("yourVersionId"), // Actual version ID of the source object.
				PartNumber:      int32(partNumber),        // Part number.
				UploadId:        oss.Ptr(uploadId),        // ID of the upload task.
			}

			// Send the multipart upload request.
			partResult, err := client.UploadPartCopy(context.TODO(), partRequest)
			if err != nil {
				log.Fatalf("failed to upload part copy %d: %v", partNumber, err)
			}

			// Record the result.
			part := oss.UploadPart{
				PartNumber: partRequest.PartNumber,
				ETag:       partResult.ETag,
			}

			// Use a mutex to protect shared data.
			mu.Lock()
			parts = append(parts, part)
			mu.Unlock()
		}(i+1, i)
	}

	// Wait for all goroutines to complete.
	wg.Wait()

	// Complete the multipart upload task.
	request := &oss.CompleteMultipartUploadRequest{
		Bucket:   oss.Ptr(destBucketName),
		Key:      oss.Ptr(destObjectName),
		UploadId: oss.Ptr(uploadId),
		CompleteMultipartUpload: &oss.CompleteMultipartUpload{
			Parts: parts,
		},
	}
	result, err := client.CompleteMultipartUpload(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to complete multipart upload %v", err)
	}

	// Display the version ID of the uploaded object.
	log.Printf("complete multipart upload result versionId:%#v\n", *result.VersionId)
}

References

  • For more information about the API operation used to copy objects, see CopyObject.

  • For more information about the API operation used to perform multipart copy, see UploadPartCopy.