Object Storage Service (OSS) supports object tagging to classify objects in a bucket. Tags are key-value pairs attached to an object. This topic shows how to add object tags using the OSS SDK for Go V2.
Prerequisites
Before you begin, ensure that you have:
The
oss:PutObjectTaggingpermission. For details, see Grant custom permissions to RAM users.Access credentials configured as environment variables. For details, see Configure access credentials.
Usage notes
The sample code uses the region ID
cn-hangzhoufor the China (Hangzhou) region. By default, the samples use public endpoints. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For the full list of regions and endpoints, see OSS regions and endpoints.Tags are specified as a URL-encoded string in
key=valueformat, with multiple tags separated by&— for example,tag1=value1&tag2=value2.
Add tags when you upload an object
Add tags to an object during a simple upload
Use the Tagging field in PutObjectRequest to attach tags at upload time.
package main
import (
"context"
"flag"
"log"
"strings"
"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 in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// The init function is 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 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 the object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
Body: strings.NewReader(content), // The content to upload.
Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual object tags.
}
// Execute 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)
}Add tags to an object during a multipart upload
Use the Tagging field in InitiateMultipartUploadRequest to attach tags when initiating a multipart upload. Tags set at initiation apply to the final assembled object.
package main
import (
"bufio"
"bytes"
"context"
"flag"
"io"
"log"
"os"
"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 // The region in which the bucket is located.
bucketName string // The name of the source bucket.
objectName string // The name of the source object.
)
// The init function is 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 source bucket.")
flag.StringVar(&objectName, "object", "", "The name of the source object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Define the upload ID.
var uploadId string
// Check whether the name of the source bucket is empty.
if len(bucketName) == 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")
}
// Check whether the name of the source object is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source 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)
// Initialize the multipart upload request.
initRequest := &oss.InitiateMultipartUploadRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual object tags.
}
// Execute the request to initiate the multipart upload.
initResult, err := client.InitiateMultipartUpload(context.TODO(), initRequest)
if err != nil {
log.Fatalf("failed to initiate multipart upload %v", err)
}
// Print the result of the multipart upload initialization.
log.Printf("initiate multipart upload result:%#v\n", *initResult.UploadId)
uploadId = *initResult.UploadId
// Initialize the wait group and mutex.
var wg sync.WaitGroup
var parts []oss.UploadPart
count := 3
var mu sync.Mutex
// Read the content of the local file into memory. Replace <local-file-path> with the actual path.
file, err := os.Open("<local-file-path>")
if err != nil {
log.Fatalf("failed to open local file %v", err)
}
defer file.Close()
bufReader := bufio.NewReader(file)
content, err := io.ReadAll(bufReader)
if err != nil {
log.Fatalf("failed to read local file %v", err)
}
log.Printf("file size: %d\n", len(content))
// Calculate the size of each part.
chunkSize := len(content) / count
if chunkSize == 0 {
chunkSize = 1
}
// Start multiple goroutines to upload parts.
for i := 0; i < count; i++ {
start := i * chunkSize
end := start + chunkSize
if i == count-1 {
end = len(content)
}
wg.Add(1)
go func(partNumber int, start, end int) {
defer wg.Done()
// Create a request to upload a part.
partRequest := &oss.UploadPartRequest{
Bucket: oss.Ptr(bucketName), // The name of the destination bucket.
Key: oss.Ptr(objectName), // The name of the destination object.
PartNumber: int32(partNumber), // The part number.
UploadId: oss.Ptr(uploadId), // The upload ID.
Body: bytes.NewReader(content[start:end]), // The content of the part.
}
// Send the request to upload the part.
partResult, err := client.UploadPart(context.TODO(), partRequest)
if err != nil {
log.Fatalf("failed to upload part %d: %v", partNumber, err)
}
// Record the result of the part upload.
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, start, end)
}
// Wait for all goroutines to complete.
wg.Wait()
// Complete the multipart upload.
request := &oss.CompleteMultipartUploadRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
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)
}
// Print the result of the completed multipart upload.
log.Printf("complete multipart upload result:%#v\n", result)
}Add tags to an object during an append upload
Use the Tagging field in the first AppendObjectRequest to attach tags.
package main
import (
"context"
"flag"
"log"
"strings"
"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
bucketName string
objectName string
)
// The init function is 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()
// Define the initial position for appending the file.
var (
position = int64(0)
)
// 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)
// Define the content to append.
content := "hi append object"
// Create an AppendObject request.
request := &oss.AppendObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
Position: oss.Ptr(position),
Body: strings.NewReader(content),
Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual object tags.
}
// Execute the first AppendObject request and process the result.
// The position of the first append upload is 0. The return value contains the position for the next append upload.
result, err := client.AppendObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to append object %v", err)
}
// Create the second AppendObject request.
request = &oss.AppendObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
Position: oss.Ptr(result.NextPosition), // Obtain NextPosition from the return value of the first AppendObject request.
Body: strings.NewReader("hi append object"),
}
// Execute the second AppendObject request and process the result.
result, err = client.AppendObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to append object %v", err)
}
log.Printf("append object result:%#v\n", result)
}Add tags to an object when you copy the object
Set TaggingDirective to Replace and specify tags in the CopyObjectRequest to apply new tags to the copied object instead of inheriting the source object's tags.
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 in which the bucket is located.
srcBucketName string // The name of the source bucket.
srcObjectName string // The name of the source object.
destBucketName string // The name of the destination bucket.
destObjectName string // The name of the destination object.
)
// The init function is 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 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 name of the source object is empty.
if len(srcObjectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source object name required")
}
// Check whether the name of the destination object 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 a request to copy the object.
copyRequest := &oss.CopyObjectRequest{
Bucket: oss.Ptr(destBucketName), // The name of the destination bucket.
Key: oss.Ptr(destObjectName), // The name of the destination object.
SourceKey: oss.Ptr(srcObjectName), // The name of the source object.
SourceBucket: oss.Ptr(srcBucketName), // The name of the source bucket.
StorageClass: oss.StorageClassStandard, // Set the storage class to Standard.
TaggingDirective: oss.Ptr("Replace"), // Do not copy the tags of the source object.
Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual object tags.
}
// Execute the copy operation and process the result.
copyResult, err := client.CopyObject(context.TODO(), copyRequest)
if err != nil {
log.Fatalf("failed to copy object: %v", err)
}
// Print the result of the copy operation.
log.Printf("copy object result:%#v\n", copyResult)
}Add tags to or modify the tags of an uploaded object
Use PutObjectTagging to add or update tags on an object that is already uploaded.
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 in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// The init function is 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 region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name 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 set object tags.
putRequest := &oss.PutObjectTaggingRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
Tagging: &oss.Tagging{
TagSet: &oss.TagSet{
Tags: []oss.Tag{
{
Key: oss.Ptr("k1"), // The tag key.
Value: oss.Ptr("v1"), // The tag value.
},
{
Key: oss.Ptr("k2"), // The tag key.
Value: oss.Ptr("v2"), // The tag value.
},
},
},
},
}
// Send the request to set object tags.
putResult, err := client.PutObjectTagging(context.TODO(), putRequest)
if err != nil {
log.Fatalf("failed to put object tagging %v", err)
}
// Print the result of setting object tags.
log.Printf("put object tagging result:%#v\n", putResult)
}References
For the complete sample code, see the GitHub example.
For the API reference, see PutObjectTagging.