Tous les produits
Search
Centre de documentation

Object Storage Service:Ajouter des tags aux objets à l'aide du SDK OSS pour Go 2.0

Dernière mise à jour :Sep 24, 2026

Object Storage Service (OSS) vous permet d'ajouter des tags aux objets afin de les classer. Cette rubrique explique comment ajouter des tags à l'aide du SDK OSS pour Go V2.

Notes

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou correspondant à la région Chine (Hangzhou). Par défaut, le point de terminaison public permet d'accéder aux ressources d'un bucket. Pour accéder aux ressources du bucket via d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison pris en charge par Object Storage Service (OSS), consultez la page Régions et points de terminaison OSS.

  • Cette rubrique récupère les identifiants d'accès depuis des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez la section Configurer les identifiants d'accès.

  • L'autorisation oss:PutObjectTagging est requise pour appliquer des tags aux objets. Pour plus d'informations, reportez-vous à la documentation relative à l'attribution d'autorisations personnalisées aux utilisateurs RAM.

Ajouter des tags lors du chargement d'un objet

Ajouter des tags à un objet lors d'un chargement simple

Le code suivant illustre l'ajout de tags pendant le chargement de l'objet.

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

Ajouter des tags à un objet lors d'un chargement multipartie

Le code ci-dessous montre comment ajouter des tags lors d'un chargement multipartie.

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

Ajouter des tags à un objet lors d'un chargement par ajout (append)

L'extrait de code suivant détaille l'ajout de tags durant un chargement par ajout.

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

Ajouter des tags à un objet lors de sa copie

Voici comment ajouter des tags lors de la copie d'un objet.

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)

}

Ajouter ou modifier les tags d'objets existants

Ajouter ou modifier les tags d'objets existants

Si un objet existant ne possède pas de tags ou si les tags ajoutés ne correspondent pas à vos besoins, vous pouvez en ajouter ou les modifier.

Le code suivant explique comment ajouter ou modifier les tags d'un objet déjà présent.

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

Références

  • Pour consulter l'exemple de code complet servant à configurer le marquage par tags des objets, rendez-vous sur GitHub.

  • Pour en savoir plus sur l'opération API permettant de configurer le marquage par tags des objets, voir la documentation PutObjectTagging.