All Products
Search
Document Center

Object Storage Service:Manage file metadata (Go SDK V2)

Last Updated:Aug 02, 2025

This topic describes how to use the OSS SDK for Go to set and obtain file metadata.

Precautions

  • The sample code in this topic uses the China (Hangzhou) region, which has the region ID cn-hangzhou, as an example. By default, a public endpoint is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint instead. For more information about the mappings between OSS regions and endpoints, see Regions and endpoints.

  • This topic provides examples of how to obtain access credentials from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • To set file metadata, you must have the oss:PutObject permission. To obtain file metadata, you must have the oss:GetObject permission. For more information, see Grant custom permissions to a RAM user.

Set metadata when you upload a file

Set metadata when you upload a file

The following sample code shows how to set metadata by calling the PutObject operation. You can set metadata such as the expiration time of a file, the access control list (ACL) of a file to public-read, or custom metadata to identify the purpose or properties of the file. You can use the same method to set metadata for other upload operations.

package main

import (
	"context"
	"flag"
	"log"
	"strings"
	"time"

	"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 storage 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(&region, "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")
	}

	// Define the content to upload.
	content := "hi oss"

	// 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 upload an object.
	request := &oss.PutObjectRequest{
		Bucket:  oss.Ptr(bucketName),                                                          // The bucket name.
		Key:     oss.Ptr(objectName),                                                          // The object name.
		Body:    strings.NewReader(content),                                                   // The content to upload.
		Expires: oss.Ptr(time.Date(2038, 12, 31, 12, 0, 0, 0, time.UTC).Format(time.RFC1123)), // The expiration time of the object.
		Acl:     oss.ObjectACLPublicRead,
		Metadata: map[string]string{ // Custom metadata.
			"Author": "alibaba oss sdk", // The author of the object.
			"Date":   "2024-07-01",      // The creation date of the object.
		},
	}

	// Send the request to upload the object.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Print the result of the object upload.
	log.Printf("put object result:%#v\n", result)
}

Obtain file metadata

Use the HeadObject method to obtain all metadata of an object

You can use the following sample code to call the HeadObject method to obtain all metadata of a specified 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 // The storage 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(&region, "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 HeadObject request.
	request := &oss.HeadObjectRequest{
		Bucket:    oss.Ptr(bucketName),      // The bucket name.
		Key:       oss.Ptr(objectName),      // The object name.
	}

	// Execute the HeadObject operation and process the result.
	result, err := client.HeadObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to head object %v", err)
	}

	// Print the result of the HeadObject operation.
	log.Printf("head object result:%#v\n", result)
}

Use the GetObjectMeta method to obtain partial metadata of an object

Note

You can call the GetObjectMeta method to obtain only a subset of an object's metadata, such as the content length (ContentLength), ETag, last modified time (LastModified), last access time (LastAccessTime), version ID (VersionId), and 64-bit CRC value (HashCRC64) of the object.

You can use the following sample code to call the GetObjectMeta method to obtain partial metadata of a specified 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 // The storage 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(&region, "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 obtain the object metadata.
	request := &oss.GetObjectMetaRequest{
		Bucket:    oss.Ptr(bucketName),      // The bucket name.
		Key:       oss.Ptr(objectName),      // The object name.
	}

	// Execute the operation to obtain the object metadata and process the result.
	result, err := client.GetObjectMeta(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get object meta %v", err)
	}

	// Print the result of obtaining the object metadata.
	log.Printf("get object meta result:%#v\n", result)
}

Modify the metadata of an existing file

Use the CopyObject method to modify object metadata

The following sample code shows how to call the CopyObject method to set the metadata of the destination object during the copy operation.

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 storage region.
	srcBucketName  string // The source bucket name.
	srcObjectName  string // The source object name.
	destBucketName string // The destination bucket name.
	destObjectName string // The destination object name.
)

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

	// Check whether the region is empty.
	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 empty.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the destination object name is empty.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination 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 metadata.
	metaData := map[string]string{
		"x-oss-meta-tag1": "value1", // The metadata key is x-oss-meta-tag1, and the value is value1.
		"x-oss-meta-tag2": "value2", // The metadata key is x-oss-meta-tag2, and the value is value2.
	}

	// Create a request to copy the object.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:            oss.Ptr(destBucketName), // The destination bucket name.
		Key:               oss.Ptr(destObjectName), // The destination object name.
		SourceKey:         oss.Ptr(srcObjectName),  // The source object name.
		SourceBucket:      oss.Ptr(srcBucketName),  // The source bucket name.
		Metadata:          metaData,                // Specify the metadata of the destination object.
		MetadataDirective: oss.Ptr("Replace"),      // Do not copy the metadata of the source object.
	}

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

	log.Printf("copy object result versionId:%#v\n", copyResult)

}

Use the Copier.Copy method of the copy manager to modify object metadata

The following sample code shows how to call the Copier.Copy method of the copy manager to set the metadata of the destination object when you copy the source object. You can replace the original metadata, clear the original metadata, or update parts of the original metadata. After the copy operation is complete, you can choose whether to delete the source 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 // The storage region.
	srcBucketName  string // The source bucket name.
	srcObjectName  string // The source object name.
	destBucketName string // The destination bucket name.
	destObjectName string // The destination object name.
)

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

	// Check whether the storage region is empty.
	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 empty.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, src object name required")
	}

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

	// Configure the OSS client.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

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

	// Create a file copier.
	c := client.NewCopier()

	// Set the metadata of the destination object.
	metaData := map[string]string{
		"x-oss-meta-tag1": "value1",
		"x-oss-meta-tag2": "value2",
	}
	// Build a request to copy the object.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:       oss.Ptr(destBucketName), // The destination bucket name.
		Key:          oss.Ptr(destObjectName), // The destination object name.
		SourceKey:    oss.Ptr(srcObjectName),  // The source object name.
		SourceBucket: oss.Ptr(srcBucketName),  // The source bucket name.
		Metadata:     metaData,                // Specify the metadata of the destination object.
		MetadataDirective: oss.Ptr("Replace"),  // Do not copy the metadata of the source object.
	}

	// Execute the copy object operation.
	result, err := c.Copy(context.TODO(), copyRequest)
	if err != nil {
		log.Fatalf("failed to copy object %v", err) // If the copy fails, log the error and exit.
	}

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

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

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

References

  • For more information about the API operation used to set file metadata, see PutObject.

  • For more information about the API operation used to obtain file metadata, see GetObject.