O Object Storage Service (OSS) permite adicionar tags a objetos para classificação. Este tópico descreve como adicionar tags usando o OSS SDK for Go V2.
Observações
O código de exemplo neste tópico usa o ID
cn-hangzhouda região China (Hangzhou). Por padrão, o acesso a recursos em um bucket ocorre por meio do endpoint público. Para acessar os recursos no bucket usando outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e os endpoints compatíveis com o Object Storage Service (OSS), consulte OSS regions and endpoints.Neste tópico, o código obtém as credenciais de acesso a partir de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.
A permissão
oss:PutObjectTaggingé necessária para adicionar tags a objetos. Para obter mais informações, consulte Grant custom permissions to RAM users.
Adicionar tags ao fazer upload de um objeto
Adicionar tags a um objeto em uma tarefa de upload simples
O código a seguir mostra como adicionar tags ao fazer upload do objeto.
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(®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 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)
}
Adicionar tags a um objeto ao fazer upload multipart
O código a seguir mostra como adicionar tags ao fazer upload multipart.
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(®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()
// 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)
}
Adicionar tags a um objeto ao fazer upload de append
O código a seguir mostra como adicionar tags ao fazer upload de append.
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(®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()
// 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)
}
Adicionar tags a um objeto ao copiá-lo
O código a seguir mostra como adicionar tags ao copiar um objeto.
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 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)
}
Adicionar ou modificar tags de objetos existentes
Adicionar ou modificar tags de objetos existentes
Se um objeto existente não tiver tags ou se as tags adicionadas não atenderem aos seus requisitos, adicione novas tags ou modifique as existentes.
O código a seguir mostra como adicionar ou modificar as tags de um objeto existente.
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 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)
}
Referências
Para obter o código de exemplo completo para configurar tags de objetos, acesse o GitHub.
Para obter mais informações sobre a operação de API para configurar tags de objetos, consulte PutObjectTagging.