This topic describes how to configure and query object metadata using Object Storage Service (OSS) SDK for Go Version 2.0.
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 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 configure object metadata, you must have the
oss:PutObject
permission. To query object metadata, you must have theoss:GetObject
permission. For more information, see Attach a custom policy to a RAM user.
Configure object metadata when you upload an object
Configure object metadata when you upload an object
Below is a code example of calling the PutObject operation to configure object metadata, including specifying the expiration time of the object, setting the ACL of the object to public-read, and identifying the purpose or attributes of the object using custom metadata. You can call other upload operations to configure object metadata in a similar manner.
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 // Region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Specify the init function 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 name of the bucket is specified.
if len(bucketName) == 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")
}
// Check whether the name of the object is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Specify the content that you want to upload.
content := "hi oss"
// 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 upload an object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName), // Name of the bucket.
Key: oss.Ptr(objectName), // Name of the object.
Body: strings.NewReader(content), // Content to be uploaded.
Expires: oss.Ptr(time.Date(2038, 12, 31, 12, 0, 0, 0, time.UTC).Format(time.RFC1123)), // Expiration time of the object.
Acl: oss.ObjectACLPublicRead,
Metadata: map[string]string{ // Custom metadata.
"Author": "alibaba oss sdk", // Author of the object.
"Date": "2024-07-01", // Creation date of the object.
},
}
// Execute the upload request.
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
// Log the result.
log.Printf("put object result:%#v\n", result)
}
Query object metadata
Query all metadata of an object using the HeadObject method
Below is a code example of querying all metadata of an object by using the HeadObject method.
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 bucket is located.
bucketName string // Name of the bucket.
objectName string // Name of the object.
)
// Specify the init function 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 name of the bucket is specified.
if len(bucketName) == 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")
}
// Check whether the name of the object is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, 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 HeadObject request.
request := &oss.HeadObjectRequest{
Bucket: oss.Ptr(bucketName), // Name of the bucket.
Key: oss.Ptr(objectName), // Name of the object.
}
// Perform 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)
}
// Log the result.
log.Printf("head object result:%#v\n", result)
}
Use GetObjectMeta method to obtain part of the metadata of the object
You can use the GetObjectMeta method to query only partial object metadata, including the returned content length (ContentLength), entity tag (ETag), last modified time (LastModified), last access time (LastAccessTime), version ID (VersionId), and CRC-64 hash (HashCRC64).
The following sample code provides an example on how to query the partial metadata of an object by using the GetObjectMeta method.
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 bucket is located.
bucketName string // Name of the bucket.
objectName string // Name of the object.
)
// Specify the init function 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 name of the bucket is specified.
if len(bucketName) == 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")
}
// Check whether the name of the object is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, 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 query object metadata.
request := &oss.GetObjectMetaRequest{
Bucket: oss.Ptr(bucketName), // Name of the bucket.
Key: oss.Ptr(objectName), // Name of the object.
}
// Execute the query request and process the result.
result, err := client.GetObjectMeta(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get object meta %v", err)
}
// Log the result.
log.Printf("get object meta result:%#v\n", result)
}
Modify object metadata
Use the CopyObject method to modify object metadata
Below is the sample code for configuring metadata when copying an object by using the CopyObject method.
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 bucket is located.
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(®ion, "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 is 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 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)
// Define metadata.
metaData := map[string]string{
"x-oss-meta-tag1": "value1", // The metadata key is defined as x-oss-meta-tag1, with the corresponding value set to value1.
"x-oss-meta-tag2": "value2", // The metadata key is defined as x-oss-meta-tag2, with the corresponding value set to value2.
}
// 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.
Metadata: metaData, // Specify the metadata of the destination object.
MetadataDirective: oss.Ptr("Replace"), // Metadata of the source object is not copied.
}
// Copy the source object 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 to modify object metadata
You can use the Copier.Copy method to copy a source object and configure metadata for the destination object. This process allows you to replace the original metadata with new metadata, clear the existing metadata, or update specific parts of it. You can choose whether to delete the source object after the operation is completed.
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 bucket is located.
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(®ion, "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, 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 is 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, src object name required")
}
// Check whether the name of the destination bucket is specified.
if len(destObjectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, destination object name required")
}
// Configure an OSSClient instance.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Create a Copier.
c := client.NewCopier()
// Specify the metadata of the destination object.
metaData := map[string]string{
"x-oss-meta-tag1": "value1",
"x-oss-meta-tag2": "value2",
}
// 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.
Metadata: metaData, // Specify the metadata of the destination object.
MetadataDirective: oss.Ptr("Replace"), // Metadata of the source object is not copied.
}
// Copy the object.
result, err := c.Copy(context.TODO(), copyRequest)
if err != nil {
log.Fatalf("failed to copy object %v", err) // In case of an error, log the error message and terminate the program.
}
// 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.
}
// Perform the operation.
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", result)
// Log the result of the deletion.
log.Printf("delete objects result:%#v\n", deleteResult)
}