Rename objects (OSS SDK for Go 2.0)

Updated at:
Copy as MD

OSS has no native rename operation. To rename an object, copy it to a new key with CopyObject or Copier.Copy, then delete the original.

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 Object Storage Service (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.

Sample code

Both methods follow the same two-step pattern: copy the source object to the destination key, then delete the source object.

Use the simple copy (CopyObject) method

The following example uses CopyObject to rename an object.

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.
	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 source bucket name 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 destination bucket name is not specified, the source bucket name is used.
	if len(destBucketName) == 0 {
		destBucketName = srcBucketName
	}

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

	// Check whether the destination object name 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 request to copy the object.
	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.
		StorageClass: oss.StorageClassStandard, // Set the storage class to Standard.
	}

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

	// Create a request to delete the object.
	deleteRequest := &oss.DeleteObjectRequest{
		Bucket: oss.Ptr(srcBucketName), // Name of the bucket.
		Key:    oss.Ptr(srcObjectName), // Name of the object to delete.
	}

	// Delete the object.
	deleteResult, err := client.DeleteObject(context.TODO(), deleteRequest)
	if err != nil {
		log.Fatalf("failed to delete multiple objects %v", err)
	}

	// Log the result of the copy operation.
	log.Printf("copy object result:%#v\n", copyResult)
	// Log the result of deletion.
	log.Printf("delete objects result:%#v\n", deleteResult)
}

Use the Copier

The following example uses Copier.Copy to rename an object.

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.
	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 source bucket name is specified.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

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

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

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

	// Check whether the destination object name 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 copier.
	c := client.NewCopier()

	// Create a request to copy the object.
	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.
		StorageClass: oss.StorageClassStandard, // Set the storage class to Standard.
	}

	// Copy the source object and process the results.
	result, err := c.Copy(context.TODO(), copyRequest)
	if err != nil {
		log.Fatalf("failed to copy object %v", err)
	}

	// Create a request to delete the object.
	deleteRequest := &oss.DeleteObjectRequest{
		Bucket: oss.Ptr(srcBucketName), // Name of the bucket.
		Key:    oss.Ptr(srcObjectName), // Name of the object to delete.
	}

	// Delete the object.
	deleteResult, err := client.DeleteObject(context.TODO(), deleteRequest)
	if err != nil {
		log.Fatalf("failed to delete multiple objects %v", err)
	}

	// Display the result of the copy operation.
	log.Printf("copy object result:%#v\n", result)
	// Display the result of deletion.
	log.Printf("delete objects result:%#v\n", deleteResult)
}

References

  • For more information about the API operation that you can call to rename objects by using the copier, see Copier.Copy.

  • For more information about the API operation that you can call to rename objects by using the CopyObject method, see CopyObject.