通过 CopyObject 可以在同一地域的存储桶之间拷贝对象,也可以在同一个存储桶内拷贝对象。复制时可以设置指定新的元数据信息或保持源对象的元数据信息。
package main import ( "context" "fmt" "github.com/volcengine/ve-tos-golang-sdk/v2/tos" "github.com/volcengine/ve-tos-golang-sdk/v2/tos/enum" ) func checkErr(err error) { if err != nil { if serverErr, ok := err.(*tos.TosServerError); ok { fmt.Println("Error:", serverErr.Error()) fmt.Println("Request ID:", serverErr.RequestID) fmt.Println("Response Status Code:", serverErr.StatusCode) fmt.Println("Response Header:", serverErr.Header) fmt.Println("Response Err Code:", serverErr.Code) fmt.Println("Response Err Msg:", serverErr.Message) } else if clientErr, ok := err.(*tos.TosClientError); ok { fmt.Println("Error:", clientErr.Error()) fmt.Println("Client Cause Err:", clientErr.Cause.Error()) } else { fmt.Println("Error:", err) } panic(err) } } func main() { var ( accessKey = os.Getenv("TOS_ACCESS_KEY") secretKey = os.Getenv("TOS_SECRET_KEY") // Bucket 对应的 Endpoint,以华北2(北京)为例:https://tos-cn-beijing.volces.com endpoint = "https://tos-cn-beijing.volces.com" region = "cn-beijing" // 填写 BucketName bucketName = "*** Provide your bucket name ***" dstBucketName = "*** Provide your dst bucket name ***" // 复制源对象 key srcObjectKey = "srcObjectKey" dstObjectKey = "objectKey" ctx = context.Background() ) // 初始化客户端 client, err := tos.NewClientV2(endpoint, tos.WithRegion(region), tos.WithCredentials(tos.NewStaticCredentials(accessKey, secretKey))) checkErr(err) // 同一个 Bucket 复制对象,复制对象使用原有的元数据数据 output, err := client.CopyObject(ctx, &tos.CopyObjectInput{ Bucket: bucketName, Key: dstObjectKey, SrcBucket: bucketName, SrcKey: srcObjectKey, MetadataDirective: enum.MetadataDirectiveCopy, }) checkErr(err) fmt.Println("CopyObject Request ID:", output.RequestID) // 复制对象使用指定的元数据信息 output, err = client.CopyObject(ctx, &tos.CopyObjectInput{ Bucket: dstBucketName, Key: dstObjectKey, SrcBucket: bucketName, SrcKey: srcObjectKey, MetadataDirective: enum.MetadataDirectiveReplace, // 复制时指定对象为低频存储 StorageClass: enum.StorageClassIa, // 复制时指定为私有权限 ACL: enum.ACLPrivate, }) checkErr(err) fmt.Println("CopyObject Request ID:", output.RequestID) }
关于普通拷贝的 API 文档,请参见 CopyObject。