All Products
Search
Document Center

Object Storage Service:Add tags to objects using OSS SDK for Go 2.0

Last Updated:Sep 24, 2026

Object Storage Service (OSS) allows you to add tags to objects for classification. This topic describes how to add tags using OSS SDK for Go V2.

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.

  • The oss:PutObjectTagging permission is required for tagging objects. For more information, see Grant custom permissions to RAM users.

Add tags when you upload an object

Add tags to an object in an simple upload task

The following code shows how to add tags when you upload the object.

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 // 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(&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 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 the 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 upload.
		Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

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

	// Display the results.
	log.Printf("put object result:%#v\n", result)
}

Add tags to an object when you perform multipart upload

The following code shows how to add tags when you perform multipart upload.

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 // Region in which the bucket is located.
	bucketName string // Name of the source bucket.
	objectName string // Name of the source 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(&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()

	// Specify the upload ID.
	var uploadId string

	// Check whether the name of the source bucket is specified.
	if len(bucketName) == 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")
	}

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

	// 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 tags of the object.
	}

	// Execute the request to initiate the multipart upload task.
	initResult, err := client.InitiateMultipartUpload(context.TODO(), initRequest)
	if err != nil {
		log.Fatalf("failed to initiate multipart upload %v", err)
	}

	// Display the result of initialisation.
	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 data from the local file to the memory and replace yourLocalFile with the actual path of the local file that contains the file name.
	file, err := os.Open("/Users/leyinhui/Downloads/iTerm2")
	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 for the multipart upload task.
	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 the multipart upload request.
			partRequest := &oss.UploadPartRequest{
				Bucket:     oss.Ptr(bucketName),                 // Name of the destination bucket.
				Key:        oss.Ptr(objectName),                 // Name of the destination object.
				PartNumber: int32(partNumber),                   // Number of the part.
				UploadId:   oss.Ptr(uploadId),                   // Upload ID.
				Body:       bytes.NewReader(content[start:end]), // 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)
			}

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

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

	// Wait until all goroutines are complete.
	wg.Wait()

	// Complete the multipart upload task.
	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)
	}

	// Display the results.
	log.Printf("complete multipart upload result:%#v\n", result)
}

Add tags to an object when you perform append upload

The following code shows how to add tags when you perform append upload.

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
)

// 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(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

	// Specify the position from which the append operation starts.
	var (
		position = int64(0)
	)

	// 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)

	// Specify the content that you want to append.
	content := "hi append object"

	// Create an AppendObject request to perform the first append operation.
	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 tags of the object.
	}

	// Perform the first append operation and process the results.
	// The first time an object is appended, the append operation starts at 0. The position for the next append operation is included in the response.
	result, err := client.AppendObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to append object %v", err)
	}

	// Create an AppendObject request to perform the second append operation.
	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
		Body:     strings.NewReader("hi append object"),
	}

	// Perform the second append operation and process the results.
	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

The following code shows how to add tags when you copy 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 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(&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 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 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 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.
		TaggingDirective: oss.Ptr("Replace"),                 // Ignore the tags of the source object.
		Tagging:          oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

	// 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)
	}

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

}

Add tags to or modify the tags of existing objects

Add tags to or modify the tags of existing objects

If an existing object has no tags or the added tags of the object do not meet your requirements, you can add tags to or modify the tags of the object.

The following code shows how to add tags to or modify the tags of an existing 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 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(&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 region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// 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 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 add tags.
	putRequest := &oss.PutObjectTaggingRequest{
		Bucket: oss.Ptr(bucketName), // Name of the bucket.
		Key:    oss.Ptr(objectName), // Name of the object.
		Tagging: &oss.Tagging{
			TagSet: &oss.TagSet{
				Tags: []oss.Tag{
					{
						Key:   oss.Ptr("k1"), // Tag key.
						Value: oss.Ptr("v1"), // Tag value.
					},
					{
						Key:   oss.Ptr("k2"), // Tag key.
						Value: oss.Ptr("v2"), // Tag value.
					},
				},
			},
		},
	}

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

	// Display the results.
	log.Printf("put object tagging result:%#v\n", putResult)
}

References

  • For the complete sample code that is used to configure object tagging, visit GitHub.

  • For more information about the API operation that you can call to configure object tagging, see PutObjectTagging.