使用 Go

支持将于2027年8月6日终止。 IBM Cloud® Object Storage (COS)SDK( v1 )将于 2027 年 8 月 6 日停止支持。 此日期之后,该软件将不再获得更新、安全修复或新版本发布。 我们建议迁移至 IBM Cloud Object Storage SDK Go v2,该平台性能更优、安全性更高、提供现代化的 API,并可继续获得 IBM 的支持。

IBM Cloud® Object Storage SDK for Go 提供了可充分利用 IBM Cloud Object Storage 的功能。

IBM Cloud Object Storage SDK for Go 综合全面,有许多特性和功能超出了本指南的描述范围。 有关类和方法的详细文档,请参阅 Go API 文档。 源代码可在 GitHub 代码库中找到。

获取 SDK

使用 go get 可检索 SDK 以将其添加到 GOPATH 工作空间,或检索项目的 Go 模块依赖项。 该 SDK 要求的 Go 语言最低版本为 1.10,最高版本为 1.12。 在我们的质量控制流程完成后,应支持 Go 语言的未来版本。

go get github.com/IBM/ibm-cos-sdk-go

要更新 SDK,请访问 go get -u 以获取 SDK 的最新版本。

go get -u github.com/IBM/ibm-cos-sdk-go

导入包

安装 SDK 后,需要将所需的包导入到 Go 应用程序才可使用 SDK,如以下示例所示:

import (
    "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
    "github.com/IBM/ibm-cos-sdk-go/aws"
    "github.com/IBM/ibm-cos-sdk-go/aws/session"
    "github.com/IBM/ibm-cos-sdk-go/service/s3"
)

创建客户端并获取服务凭据

为了连接到 IBM Cloud Object Storage,将通过提供凭证信息(API 密钥和服务实例标识)来创建和配置客户机。 这些值还可以自动从凭证文件或环境变量中获取。

通过创建服务凭证或通过 CLI 可以找到凭证。

图 1 显示了如何在 IBM Cloud Object Storage 门户网站中定义应用程序运行时中的环境变量的示例。 所需的变量包括:IBM_API_KEY_ID (其中包含您的服务凭据 apikey )、IBM_SERVICE_INSTANCE_ID (其中包含同样来自您的服务凭据的 resource_instance_id ),以及一个值为 IBM_AUTH_ENDPOINT 的变量,其值应与您的账户匹配,例如 https://iam.cloud.ibm.com/identity/token。 如果使用环境变量来定义应用程序凭证,请使用 WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())).,并替换配置示例中使用的类似方法。

环境变量
环境变量
环境变量

如果是从 AWS S3 进行迁移,那么还可以从 ~/.aws/credentials 中获取以下格式的凭证数据:

[default]
aws_access_key_id = {ACCESS_KEY}
aws_secret_access_key = {SECRET_ACCESS_KEY}

如果 ~/.bluemix/cos_credentials~/.aws/credentials 同时存在,那么 cos_credentials 优先。

初始化配置

// Constants for IBM COS values
const (
    apiKey            = "<API_KEY>"  // eg "0viPHOY7LbLNa9eLftrtHPpTjoGv6hbLD1QalRXikliJ"
    serviceInstanceID = "<RESOURCE_INSTANCE_ID>" // eg "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0d9003xxxxxxxxxx1c3e97696b71c:d6f04d83-6c4f-4a62-a165-696756d63903::"
    authEndpoint      = "https://iam.cloud.ibm.com/identity/token"
    serviceEndpoint   = "<SERVICE_ENDPOINT>" // eg "https://s3.us.cloud-object-storage.appdomain.cloud"
    bucketLocation    = "<LOCATION>" // eg "us"
)
// Create config
conf := aws.NewConfig().
    WithRegion("us-standard").
    WithEndpoint(serviceEndpoint).
    WithCredentials(ibmiam.NewStaticCredentials(aws.NewConfig(), authEndpoint, apiKey, serviceInstanceID)).
    WithS3ForcePathStyle(true)

为计算资源创建客户端并获取受信任的配置文件证书

客户机可通过提供服务凭证或可信配置文件凭证来创建。 本节提供以下信息 创建客户端的信息。

要连接到 IBM Cloud Object Storage,需要创建一个客户端,也可以通过提供可信配置文件凭据信息(可信配置文件 ID 和 CR 令牌文件路径)进行配置。 这些值也可以自动源自环境变量。

要创建可信概要文件,基于特定属性建立对计算资源的信任,并定义策略以分配对资源的访问权,请参阅 管理对计算资源中应用程序的访问权

要了解有关使用 Kubernetes 集群建立信任的更多信息,请参阅 在 Kubernetes 和 OpenShift 集群中使用可信概要文件

GO SDK 仅在 Kubernetes 和 OpenShift 集群中支持使用可信配置文件进行身份验证。

受信任的配置文件凭据可在应用程序运行时设置为环境变量。 所需的变量有:TRUSTED_PROFILE_ID,其中包含您的受托个人资料 ID trusted profile idCR_TOKEN_FILE_PATH,其中包含 service account token file pathIBM_SERVICE_INSTANCE_ID,其中包含您的服务凭证中的 resource_instance_id ;以及 IBM_AUTH_ENDPOINT,其中包含与您的账户相适应的值,如 https://iam.cloud.ibm.com/identity/token。 如果使用环境变量来定义应用程序凭证,请使用 WithCredentials(ibmiam.NewEnvCredentials(aws.NewConfig())).,并替换配置示例中使用的类似方法。

初始化配置

// Constants for IBM COS values
const (
    trustedProfileID  = "<TRUSTED_PROFILE_ID>"  // eg "Profile-5790481a-8fc5-46a4-bae3-d0e64ff6e0ad"
    crTokenFilePath   = "<SERVICE_ACCOUNT_TOKEN_FILE_PATH>" // "/var/run/secrets/tokens/service-account-token"
    serviceInstanceID = "<RESOURCE_INSTANCE_ID>" // "crn:v1:bluemix:public:cloud-object-storage:global:a/<CREDENTIAL_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
    authEndpoint      = "https://iam.cloud.ibm.com/identity/token"
    serviceEndpoint   = "<SERVICE_ENDPOINT>" // eg "https://s3.us.cloud-object-storage.appdomain.cloud"
    bucketLocation    = "<LOCATION>" // eg "us-standard"
)
// Create config
conf := aws.NewConfig().
    WithRegion(bucketLocation).
    WithEndpoint(serviceEndpoint).
    WithCredentials(ibmiam.NewTrustedProfileCredentialsCR(aws.NewConfig(), authEndpoint, trustedProfileID, crtokenFilePath, serviceInstanceID)).
    WithS3ForcePathStyle(true)

API-Key 和 Trusted-Profile-ID 都不能设置为环境变量。 只能设置其中一个,否则 GO SDK 就会出错。

有关端点的更多信息,请参阅端点和存储位置

创建客户端并为服务 ID 获取受托配置文件证书

现在,您可以创建一个客户端,通过使用服务 ID 和受信任配置文件来验证 IBM Cloud Object Storage。 受托配置文件使 IBM Cloud 身份能够访问账户中的资源,而无需直接成为该账户的成员。 通过将服务 ID 与受托配置文件关联,可以安全地授予其访问资源的权限,包括位于不同 IBM Cloud 账户中的资源。 更多详情,请参阅 IBM Cloud 关于创建 服务 ID 的受信任配置文件 的文档。

准备工作

  1. 在源账户中创建服务 ID
    • 在服务 ID 中,创建一个 API 密钥并记下 API 密钥值。
  2. 在目标账户中创建受托配置文件,并关联源账户中的服务 ID。 请参阅 在控制台中使用服务 ID 建立信任目标账户是包含要访问的资源的账户。
  3. 为受托配置文件分配适当的访问权限

使用服务 ID 和受托配置文件进行身份验证

设置完成后,使用 Go SDK 构建一个客户端,使用服务 ID 和可信配置文件进行身份验证。

  1. 使用可信配置文件 ID 设置客户端配置:

    package main
    import (
        "fmt"
        "os"
        "github.com/IBM/ibm-cos-sdk-go/aws"
        "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
        "github.com/IBM/ibm-cos-sdk-go/aws/session"
        "github.com/IBM/ibm-cos-sdk-go/service/s3"
    )
    const (
        serviceInstanceID  = "crn-of-target-cos-instance" // eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
        authEndpoint       = "https://iam.cloud.ibm.com/identity/token"
        serviceEndpoint   = "cos-endpoint"     //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud"
        trustedProfileId   = ""    // eg: "Profile-gxxxxx530-xxxx-xxxx-xxxx-abpxxxxb94"
        serviceIDApiKey = "api-key-of-service-id"
    )
    func TestTrustedProfile
    func main() {
        sess := session.Must(session.NewSession())
        conf := aws.NewConfig().
            WithRegion("us-south").
    WithEndpoint(serviceEndpoint).       WithCredentials(ibmiam.NewTrustedProfileCredentialsServiceIDWithTrustedProfileId(aws.NewConfig(), authEndpoint, trustedProfileId, serviceIDApiKey, serviceInstanceID)).
            WithS3ForcePathStyle(true)
        client := s3.New(sess, conf)
    }
    
  2. 使用受托配置文件名称设置客户端配置:

    package main
    import (
        "fmt"
        "os"
        "github.com/IBM/ibm-cos-sdk-go/aws"
        "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam"
        "github.com/IBM/ibm-cos-sdk-go/aws/session"
        "github.com/IBM/ibm-cos-sdk-go/service/s3"
    )
    const (
        serviceInstanceID  = "crn-of-target-cos-instance" //eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
        authEndpoint       = "https://iam.cloud.ibm.com/identity/token"
        serviceEndpoint   = "cos-endpoint"     //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud"
        trustedProfileName   = "name-of-trusted-profile"
        accountId = "account-id-that-owns-trusted-profile"
        serviceIDApiKey = "api-key-of-service-id"
    )
    func TestTrustedProfile
    func main() {
        sess := session.Must(session.NewSession())
        conf := aws.NewConfig().
            WithRegion("us-south").
            WithEndpoint(serviceEndpoint).
            WithCredentials(ibmiam.NewTrustedProfileCredentialsServiceIDWithTrustedProfileName(aws.NewConfig(), authEndpoint, trustedProfileName, accountId, serviceIDApiKey, serviceInstanceID)).
            WithS3ForcePathStyle(true)
        client := s3.New(sess, conf)
    }
    

使用受托配置文件名称时,还必须提供拥有受托配置文件的账户 ID。

受信任的配置文件凭据也可以在运行时通过环境变量提供。

  1. 使用环境变量和可信配置文件 ID 配置客户端:

    1. 在运行环境中设置这些环境变量。

      export IBM_SERVICE_INSTANCE_ID="crn-of-target-cos-instance" //eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
      export TRUSTED_PROFILE_ID="id-of-trusted-profile"
      export IBM_SERVICE_ID_API_KEY="api-key-of-service-id"
      export IBM_AUTH_ENDPOINT="https://iam.cloud.ibm.com/identity/token"
      
    2. 配置客户机。

      const (
      serviceEndpoint   = "cos-endpoint"     //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud"
      )
      conf := cltMain().NewConfigNoSSL()
      conf.WithRegion(cltMain().DefaultRegion()).
          WithEndpoint(serviceEndpoint).
          WithS3ForcePathStyle(true)
      sess := session.Must(session.NewSession())
      client := s3.New(sess, conf)
      
  2. 使用环境变量和受信任的配置文件名称配置客户端:

    1. 在运行环境中设置这些环境变量。

      export IBM_SERVICE_INSTANCE_ID="crn-of-target-cos-instance" //eg: "crn:v1:bluemix:public:cloud-object-storage:global:a/<ACCOUNT_ID_AS_GENERATED>:<SERVICE_ID_AS_GENERATED>::"
      export TRUSTED_PROFILE_NAME="name-of-trusted-profile"
      export IBM_SERVICE_ID_API_KEY="api-key-of-service-id"
      export IBM_AUTH_ENDPOINT="https://iam.cloud.ibm.com/identity/token"
      export IAM_ACCOUNT_ID="account-id-owns-trusted-profile"
      
    2. 配置客户机。

      const (
      serviceEndpoint   = "cos-endpoint"     //eg :"https://s3.us-south.cloud-object-storage.appdomain.cloud"
      )
      conf := cltMain().NewConfigNoSSL()
      conf.WithRegion(cltMain().DefaultRegion()).
          WithEndpoint(serviceEndpoint).
          WithS3ForcePathStyle(true)
      sess := session.Must(session.NewSession())
      client := s3.New(sess, conf)
      

用实际的 CRN、API 密钥、配置文件名称或 ID、端点和账户 ID 替换占位符值。

代码示例

创建新存储区

有关 LocationConstraint 的有效配置代码列表,请参阅 《存储类指南》

样本会根据样本配置为 Cold Vault 存储使用适当的位置限制。 您的位置和配置可能会有所不同。

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Bucket Names
    newBucket := "<NEW_BUCKET_NAME>"
    newColdBucket := "<NEW_COLD_BUCKET_NAME>"
    input := &s3.CreateBucketInput{
        Bucket: aws.String(newBucket),
    }
    client.CreateBucket(input)
    input2 := &s3.CreateBucketInput{
        Bucket: aws.String(newColdBucket),
        CreateBucketConfiguration: &s3.CreateBucketConfiguration{
            LocationConstraint: aws.String("us-cold"),
        },
    }
    client.CreateBucket(input2)
    d, _ := client.ListBuckets(&s3.ListBucketsInput{})
    fmt.Println(d)
}

列出可用存储区

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Call Function
    d, _ := client.ListBuckets(&s3.ListBucketsInput{})
    fmt.Println(d)
}

将对象上传到存储区

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Variables and random content to sample, replace when appropriate
    bucketName := "<BUCKET_NAME>"
    key := "<OBJECT_KEY>"
    content := bytes.NewReader([]byte("<CONTENT>"))
    input := s3.PutObjectInput{
        Bucket:        aws.String(bucketName),
        Key:           aws.String(key),
        Body:          content,
    }
    // Call Function to upload (Put) an object
    result, _ := client.PutObject(&input)
    fmt.Println(result)
}

列出桶中的项目(列出对象 V2 )

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Bucket Name
    Bucket := "<BUCKET_NAME>"
    // Call Function
    Input := &s3.ListObjectsV2Input{
            Bucket: aws.String(Bucket),
        }
    l, e := client.ListObjectsV2(Input)
    fmt.Println(l)
    fmt.Println(e) // prints "<nil>"
}
// The response should be formatted like the following example:
//{
// 	Contents: [{
// 		ETag: "\"dbxxxxx53xxx7d06378204e3xxxxxx9f\"",
// 		Key: "file1.json",
// 		LastModified: 2019-10-15 22:22:52.62 +0000 UTC,
// 		Size: 1045,
// 		StorageClass: "STANDARD"
// 	  },{
// 		ETag: "\"6e1xxxxx63xxxdefb440f72axxxxxxc2\"",
// 		Key: "file2.json",
// 		LastModified: 2019-10-15 23:08:10.074 +0000 UTC,
// 		Size: 1045,
// 		StorageClass: "STANDARD"
// 	  }],
// 	Delimiter: "",
// 	IsTruncated: false,
// 	KeyCount: 2,
// 	MaxKeys: 1000,
// 	Name: "<BUCKET_NAME>",
// 	Prefix: ""
//}

获取对象的内容

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Variables
    bucketName := "<NEW_BUCKET_NAME>"
    key := "<OBJECT_KEY>"
    // users will need to create bucket, key (flat string name)
    Input := s3.GetObjectInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(key),
    }
    // Call Function
    res, _ := client.GetObject(&Input)
    body, _ := ioutil.ReadAll(res.Body)
    fmt.Println(body)
}

从存储区中删除对象

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Bucket Name
    bucket := "<BUCKET_NAME>"
    input := &s3.DeleteObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String("<OBJECT_KEY>"),
    }
    d, _ := client.DeleteObject(input)
    fmt.Println(d)
}

从存储区中删除多个对象

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Bucket Name
    bucket := "<BUCKET_NAME>"
    input := &s3.DeleteObjectsInput{
        Bucket: aws.String(bucket),
        Delete: &s3.Delete{
            Objects: []*s3.ObjectIdentifier{
                {
                    Key: aws.String("<OBJECT_KEY1>"),
                },
                {
                    Key: aws.String("<OBJECT_KEY2>"),
                },
                {
                    Key: aws.String("<OBJECT_KEY3>"),
                },
            },
            Quiet: aws.Bool(false),
        },
    }
    d, _ := client.DeleteObjects(input)
    fmt.Println(d)
}

删除存储区

func main() {
    // Bucket Name
    bucket := "<BUCKET_NAME>"
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    input := &s3.DeleteBucketInput{
        Bucket: aws.String(bucket),
    }
    d, _ := client.DeleteBucket(input)
    fmt.Println(d)
}

运行手动分块上传

func main() {
    // Variables
    bucket := "<BUCKET_NAME>"
    key := "<OBJECT_KEY>"
    content := bytes.NewReader([]byte("<CONTENT>"))
    input := s3.CreateMultipartUploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    }
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    upload, _ := client.CreateMultipartUpload(&input)
    uploadPartInput := s3.UploadPartInput{
        Bucket:     aws.String(bucket),
        Key:        aws.String(key),
        PartNumber: aws.Int64(int64(1)),
        UploadId:   upload.UploadId,
        Body:          content,
    }
    var completedParts []*s3.CompletedPart
    completedPart, _ := client.UploadPart(&uploadPartInput)
    completedParts = append(completedParts, &s3.CompletedPart{
        ETag:       completedPart.ETag,
        PartNumber: aws.Int64(int64(1)),
    })
    completeMPUInput := s3.CompleteMultipartUploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
        MultipartUpload: &s3.CompletedMultipartUpload{
            Parts: completedParts,
        },
        UploadId: upload.UploadId,
    }
    d, _ := client.CompleteMultipartUpload(&completeMPUInput)
    fmt.Println(d)
}

使用 Key Protect

可以将 Key Protect 添加到存储区,以管理加密密钥。 IBM Cloud Object Storage 中所有数据均经过加密,但 Key Protect 提供了一项服务,可通过集中式服务生成、轮换加密密钥并控制对其的访问权限。

准备工作

要创建一个启用了 Key-Protect 功能的存储桶,需要以下项目:

检索根密钥 CRN

  1. 检索 Key Protect 服务的实例标识
  2. 使用 Key Protect API 来检索所有可用密钥
  3. 获取您用于在存储桶上启用 Key Protect 功能的根密钥的CRN。 CRN的外观如下所示:

crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234

创建启用了 Key Protect 的存储区

func main() {
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Bucket Names
    newBucket := "<NEW_BUCKET_NAME>"
    fmt.Println("Creating new encrypted bucket:", newBucket)
    input := &s3.CreateBucketInput{
        Bucket: aws.String(newBucket),
        IBMSSEKPCustomerRootKeyCrn: aws.String("<ROOT-KEY-CRN>"),
        IBMSSEKPEncryptionAlgorithm:aws.String("<ALGORITHM>"),
    }
    client.CreateBucket(input)
    // List Buckets
    d, _ := client.ListBuckets(&s3.ListBucketsInput{})
    fmt.Println(d)
}

键值

  • <NEW_BUCKET_NAME>- 新存储桶的名称。
  • <ROOT-KEY-CRN>- 从 Key Protect 服务获取的根密钥的CRN。
  • <ALGORITHM>- 用于对添加到存储桶中的新对象进行加密的算法(默认值为 AES256 )。

使用传输管理器

func main() {
    // Variables
    bucket := "<BUCKET_NAME>"
    key := "<OBJECT_KEY>"
    // Create client
    sess := session.Must(session.NewSession())
    client := s3.New(sess, conf)
    // Create an uploader with S3 client and custom options
    uploader := s3manager.NewUploaderWithClient(client, func(u *s3manager.Uploader) {
        u.PartSize = 5 * 1024 * 1024 // 64MB per part
    })
    // make a buffer of 5MB
    buffer := make([]byte, 15*1024*1024, 15*1024*1024)
    random := rand.New(rand.NewSource(time.Now().Unix()))
    random.Read(buffer)
    input := &s3manager.UploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
        Body:   io.ReadSeeker(bytes.NewReader(buffer)),
    }
    // Perform an upload.
    d, _ := uploader.Upload(input)
    fmt.Println(d)
    // Perform upload with options different than the those in the Uploader.
    f, _ := uploader.Upload(input, func(u *s3manager.Uploader) {
        u.PartSize = 10 * 1024 * 1024 // 10MB part size
        u.LeavePartsOnError = true    // Don't delete the parts if the upload fails.
    })
    fmt.Println(f)
}

获取扩展列表

func main() {
// Create client
        sess := session.Must(session.NewSession())
        client := s3.New(sess, conf)
        input := new(s3.ListBucketsExtendedInput).SetMaxKeys(<MAX_KEYS>).SetMarker("<MARKER>").SetPrefix("<PREFIX>")
        output, _ := client.ListBucketsExtended(input)
        jsonBytes, _ := json.MarshalIndent(output, " ", " ")
        fmt.Println(string(jsonBytes))
}

键值

  • <MAX_KEYS>- 请求中要检索的桶的最大数量。
  • <MARKER>- 开始列出的存储桶名称(跳过此存储桶之前的存储桶)。
  • <PREFIX- 仅包含名称以此前缀开头的存储桶。

使用分页获取扩展列表

func main() {
	// Create client
	sess := session.Must(session.NewSession())
	client := s3.New(sess, conf)
    i := 0
    input := new(s3.ListBucketsExtendedInput).SetMaxKeys(<MAX_KEYS>).SetMarker("<MARKER>").SetPrefix("<PREFIX>")
	output, _ := client.ListBucketsExtended(input)
	for _, bucket := range output.Buckets {
		fmt.Println(i, "\t\t", *bucket.Name, "\t\t", *bucket.LocationConstraint, "\t\t", *bucket.CreationDate)
	}
}

键值

  • <MAX_KEYS>- 请求中要检索的桶的最大数量。
  • <MARKER>- 开始列出的存储桶名称(跳过此存储桶之前的存储桶)。
  • <PREFIX- 仅包含名称以此前缀开头的存储桶。

归档层支持

您可以在指定的时间长度之后或在指定的日期之后自动归档对象。 归档后,可根据需要复原对象的临时副本以进行访问。

恢复一个或多个对象的临时副本所需的时间可能长达 12 小时。

要使用所提供的示例,请提供自己的配置,包括替换 <apikey> 和其他带括号的 <...> 信息,但要记住,使用环境变量更安全,而且不应将凭据放在将被版本控制的代码中。

通过在客户机实例上调用 PutBucketLifecycleConfiguration 方法在存储区级别设置归档策略。 新添加或修改的归档策略将应用于上传的新对象,但不会影响现有对象。

func main() {
	// Create Client
	sess := session.Must(session.NewSession())
	client := s3.New(sess, conf)
	// PUT BUCKET LIFECYCLE CONFIGURATION
	// Replace <BUCKET_NAME> with the name of the bucket
	lInput := &s3.PutBucketLifecycleConfigurationInput{
		Bucket: aws.String("<BUCKET_NAME>"),
		LifecycleConfiguration: &s3.LifecycleConfiguration{
			Rules: []*s3.LifecycleRule{
				{
					Status: aws.String("Enabled"),
					Filter: &s3.LifecycleRuleFilter{},
					ID:     aws.String("id3"),
					Transitions: []*s3.Transition{
						{
							Days:         aws.Int64(5),
							StorageClass: aws.String("Glacier"),
						},
					},
				},
			},
		},
	}
	l, e := client.PutBucketLifecycleConfiguration(lInput)
	fmt.Println(l) // should print an empty bracket
	fmt.Println(e) // should print <nil>
	// GET BUCKET LIFECYCLE CONFIGURATION
	gInput := &s3.GetBucketLifecycleConfigurationInput{
		Bucket: aws.String("<bucketname>"),
	}
	g, e := client.GetBucketLifecycleConfiguration(gInput)
	fmt.Println(g)
	fmt.Println(e) // see response for results
    // RESTORE OBJECT
    // Replace <OBJECT_KEY> with the appropriate key
    rInput := &s3.RestoreObjectInput{
        Bucket: aws.String("<BUCKET_NAME>"),
        Key:    aws.String("<OBJECT_KEY>"),
        RestoreRequest: &s3.RestoreRequest{
            Days: aws.Int64(100),
            GlacierJobParameters: &s3.GlacierJobParameters{
                Tier: aws.String("Bulk"),
            },
        },
    }
    r, e := client.RestoreObject(rInput)
    fmt.Println(r)
    fmt.Println(e)
}

此处举例说明了典型的响应。

 {
   Rules: [{
       Filter: {
       },
       ID: "id3",
       Status: "Enabled",
       Transitions: [{
           Days: 5,
           StorageClass: "GLACIER"
         }]
     }]
 }

不可变对象存储器

用户可以配置具有不可变 Object Storage 策略的存储桶,以防止对象在规定时间内被修改或删除。 可以按对象指定保留期,或者对象可以继承存储区上设置的缺省保留期。 还可以设定开放和永久的保留期。 不可改变的 Object Storage 符合 SEC 管理记录保留时间的规则,并且 IBM Cloud 管理员无法绕过这些限制。

Immutable Object Storage 现阶段不支持通过 SDK 上传对象或目录的 Aspera 传输。

func main() {
	// Create Client
	sess := session.Must(session.NewSession())
	client := s3.New(sess, conf)
	// Create a bucket
	input := &s3.CreateBucketInput{
		Bucket: aws.String("<BUCKET_NAME>"),
	}
	d, e := client.CreateBucket(input)
	fmt.Println(d) // should print an empty bracket
	fmt.Println(e) // should print <nil>
	// PUT BUCKET PROTECTION CONFIGURATION
	pInput := &s3.PutBucketProtectionConfigurationInput{
		Bucket: aws.String("<BUCKET_NAME>"),
		ProtectionConfiguration: &s3.ProtectionConfiguration{
			DefaultRetention: &s3.BucketProtectionDefaultRetention{
				Days: aws.Int64(100),
			},
			MaximumRetention: &s3.BucketProtectionMaximumRetention{
				Days: aws.Int64(1000),
			},
			MinimumRetention: &s3.BucketProtectionMinimumRetention{
				Days: aws.Int64(10),
			},
			Status: aws.String("Retention"),
		},
	}
	p, e := client.PutBucketProtectionConfiguration(pInput)
	fmt.Println(p)
	fmt.Println(e) // see response for results
	// GET BUCKET PROTECTION CONFIGURATION
	gInput := &s3.GetBucketProtectionConfigurationInput{
		Bucket: aws.String("<BUCKET_NAME>"),
	}
	g, e := client.GetBucketProtectionConfiguration(gInput)
	fmt.Println(g)
	fmt.Println(e)
}

此处举例说明了典型的响应。

 {
   ProtectionConfiguration: {
     DefaultRetention: {
       Days: 100
     },
     MaximumRetention: {
       Days: 1000
     },
     MinimumRetention: {
       Days: 10
     },
     Status: "COMPLIANCE"
   }
 }

创建托管静态 Web 站点

此操作需要许可权,因为通常仅允许存储区所有者配置存储区以托管静态 Web 站点。 这些参数确定站点访问者的缺省后缀以及此处包含的可选错误文档以完成示例。

func main() {
	// Create Client
	sess := session.Must(session.NewSession())
	client := s3.New(sess, conf)
	// Create a bucket
	input := &s3.CreateBucketInput{
		Bucket: aws.String("<BUCKET_NAME>"),
	}
	d, e := client.CreateBucket(input)
	fmt.Println(d) // should print an empty bracket
	fmt.Println(e) // should print <nil>
	// PUT BUCKET WEBSITE
	pInput := s3.PutBucketWebsiteInput{
        Bucket: input,
        WebsiteConfiguration: &s3.WebsiteConfiguration{
            IndexDocument: &s3.IndexDocument{
                Suffix: aws.String("index.html"),
            },
        },
    }
    pInput.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{
        Key: aws.String("error.html"),
    }
    p, e := client.PutBucketWebsite(&params)
	fmt.Println(p)
	fmt.Println(e) // see response for results
}

创建备份策略

func main() {
    apiKey := "<API_KEY>"
    policyName := "<POLICY_NAME>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    backupVaultCrn := "<BACKUP_VAULT_CRN>"
    // Initialize authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize ResourceConfiguration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Create Backup Policy
    // Define initial retention
    initialRetention := &resourceconfigurationv1.DeleteAfterDays{
        DeleteAfterDays: core.Int64Ptr(1),
    }
    // Create backup policy
    createBackupPolicyOptions := &resourceconfigurationv1.CreateBackupPolicyOptions{
        Bucket:               core.StringPtr(sourceBucketName),
        PolicyName:           core.StringPtr(policyName),
        TargetBackupVaultCrn: core.StringPtr(backupVaultCrn),
        BackupType:           core.StringPtr("continuous"),
        InitialRetention:     initialRetention,
    }
    createResponse, _, err := rcClient.CreateBackupPolicy(createBackupPolicyOptions)
    if err != nil {
        log.Fatalf("Failed to create backup policy: %v", err)
    }
    fmt.Println("Backup policy created:")
    fmt.Println(createResponse)
}

列出备份策略

func main() {
    apiKey := "<API_KEY>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    // Initialize IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize ResourceConfiguration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // List all backup policies
    listBackupPoliciesOptions := &resourceconfigurationv1.ListBackupPoliciesOptions{
        Bucket: core.StringPtr(sourceBucketName),
    }
    result, _, err := rcClient.ListBackupPolicies(listBackupPoliciesOptions)
    if err != nil {
        log.Fatalf("Failed to list backup policies: %v", err)
    }
    fmt.Println(result.BackupPolicies)
}

制定备份政策

func main() {
    apiKey := "<API_KEY>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    policyId := "<POLICY_ID>"
    // Initialize IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize ResourceConfiguration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Fetch backup policy using policy ID
    getBackupPolicyOptions := &resourceconfigurationv1.GetBackupPolicyOptions{
        Bucket:   core.StringPtr(sourceBucketName),
        PolicyID: core.StringPtr(policyId),
    }
    getResponse, _, err := rcClient.GetBackupPolicy(getBackupPolicyOptions)
    if err != nil {
        log.Fatalf("Failed to fetch backup policy: %v", err)
    }
    fmt.Println("\nFetched Backup Policy Details:")
    fmt.Println(getResponse)
}

删除备份策略

func main() {
    apiKey := "<API_KEY>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    backupVaultCrn := "<BACKUP_VAULT_CRN>"
    policyId := "<POLICY_ID>"
    // Initialize IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize ResourceConfiguration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Delete the created backup policy
    deleteBackupPolicyOptions := &resourceconfigurationv1.DeleteBackupPolicyOptions{
        Bucket:   core.StringPtr(sourceBucketName),
        PolicyID: core.StringPtr(policyId),
    }
    _, err = rcClient.DeleteBackupPolicy(deleteBackupPolicyOptions)
    if err != nil {
        log.Fatalf("Failed to delete backup policy: %v", err)
    }
    fmt.Printf("Backup policy '%s' deleted successfully.\n", policyId)
}

创建备份库

func main() {
    apiKey := "<API_KEY>"
    serviceInstanceID := "<SERVICE_INSTANCE_ID>"
    region := "<REGION>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Create backup vault
    createBackupVaultOptions := &resourceconfigurationv1.CreateBackupVaultOptions{
        ServiceInstanceID: core.StringPtr(serviceInstanceID),
        BackupVaultName:   core.StringPtr(backupVaultName),
        Region:            core.StringPtr(region),
    }
    createResponse, _, err := rcClient.CreateBackupVault(createBackupVaultOptions)
    if err != nil {
        log.Fatalf("Failed to create backup vault: %v", err)
    }
    fmt.Printf(createResponse)
}

列表备份库

func main() {
    apiKey := "<API_KEY>"
    serviceInstanceID := "<SERVICE_INSTANCE_ID>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // List backup vaults
    listBackupVaultsOptions := &resourceconfigurationv1.ListBackupVaultsOptions{
        ServiceInstanceID: core.StringPtr(serviceInstanceID),
    }
    result, _, err := rcClient.ListBackupVaults(listBackupVaultsOptions)
    if err != nil {
        log.Fatalf("Failed to list backup vaults: %v", err)
    }
    fmt.Println(result.BackupVaults)
}

获取备份库

func main() {
    apiKey := "<API_KEY>"
    serviceInstanceID := "<SERVICE_INSTANCE_ID>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Get backup vault details
    getBackupVaultOptions := &resourceconfigurationv1.GetBackupVaultOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
    }
    result, _, err := rcClient.GetBackupVault(getBackupVaultOptions)
    if err != nil {
        log.Fatalf("Failed to get backup vault details: %v", err)
    }
    fmt.Println(result.GetBackupVault)
}

更新备份库

func main() {
    apiKey := "<API_KEY>"
    serviceInstanceID := "<SERVICE_INSTANCE_ID>"
    region := "<REGION>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Update backup vault: disable activity tracking and metrics monitoring
    backupVaultPatch := &resourceconfigurationv1.BackupVaultPatch{
        ActivityTracking: &resourceconfigurationv1.BackupVaultActivityTracking{
            ManagementEvents: core.BoolPtr(false),
        },
        MetricsMonitoring: &resourceconfigurationv1.BackupVaultMetricsMonitoring{
            UsageMetricsEnabled: core.BoolPtr(false),
        },
    }
    bucketPatchModelAsPatch, _ := backupVaultPatch.AsPatch()
    updateBucketBackupVaultOptions := &resourceconfigurationv1.UpdateBackupVaultOptions{
        BackupVaultName:  core.StringPtr(backupVaultName),
        BackupVaultPatch: bucketPatchModelAsPatch,
    }
    _, patchResponse, err := rcClient.UpdateBackupVault(updateBucketBackupVaultOptions)
    if err != nil {
        log.Fatalf("Failed to update backup vault: %v", err)
    }
  fmt.Println(patchResponse)
}

删除备份库

func main() {
    apiKey := "<API_KEY>"
    serviceInstanceID := "<SERVICE_INSTANCE_ID>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Delete backup vault
    deleteBackupVaultOptions := &resourceconfigurationv1.DeleteBackupVaultOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
    }
    _, err = rcClient.DeleteBackupVault(deleteBackupVaultOptions)
    if err != nil {
        log.Fatalf("Failed to delete backup vault: %v", err)
    }
}

列表恢复范围

func main() {
    apiKey := "<API_KEY>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    backupVaultCrn := "<BACKUP_VAULT_CRN>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // List recovery ranges
    listRecoveryRangesOptions := &resourceconfigurationv1.ListRecoveryRangesOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
    }
    recoveryRangesResponse, _, err := rcClient.ListRecoveryRanges(listRecoveryRangesOptions)
    if err != nil {
        log.Fatalf("Failed to list recovery ranges: %v", err)
    }
fmt.Println(recoveryRangesResponse)
}

获取恢复范围

func main() {
    apiKey := "<API_KEY>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    backupVaultCrn := "<BACKUP_VAULT_CRN>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Fetch details of the recovery range
    getRecoveryRangeOptions := &resourceconfigurationv1.GetSourceResourceRecoveryRangeOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
        RecoveryRangeID: core.StringPtr(recoveryRangeId),
    }
    getRecoveryRangeResponse, _, err := rcClient.GetSourceResourceRecoveryRange(getRecoveryRangeOptions)
    if err != nil {
        log.Fatalf("Failed to fetch recovery range: %v", err)
    }
fmt.Println(recoveryRangesResponse)
}

更新恢复范围

func main() {
    // Config values
    apiKey := "<API_KEY>"
    sourceBucketName := "<SOURCE_BUCKET_NAME>"
    backupVaultCRN := "<BACKUP_VAULT_CRN>"
    backupVaultName := "<BACKUP_VAULT_NAME>"
    // Setup IAM Authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    options := &resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    }
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1UsingExternalConfig(options)
    if err != nil {
        log.Fatalf("Failed to create Resource Configuration client: %v", err)
    }
    // Patch the recovery range (update retention to 99 days)
    patchOpts := &resourceconfigurationv1.PatchSourceResourceRecoveryRangeOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
        RecoveryRangeID: core.StringPtr(recoveryRangeID),
        RecoveryRangePatch: &resourceconfigurationv1.RecoveryRangePatch{
            Retention: &resourceconfigurationv1.DeleteAfterDays{
                DeleteAfterDays: core.Int64Ptr(99),
            },
        },
    }
    patchResp, _, err := rcClient.PatchSourceResourceRecoveryRange(patchOpts)
    if err != nil {
        log.Fatalf("Failed to patch recovery range: %v", err)
    }
    fmt.Println("Successfully patched recovery range:")
    fmt.Printf("%+v\n", patchResp)
}

启动还原

func main() {
    // Setup authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Initiate restore
    restoreOptions := &resourceconfigurationv1.CreateRestoreOptions{
        BackupVaultName:    core.StringPtr(backupVaultName),
        RecoveryRangeID:    core.StringPtr(recoveryRangeId),
        RestoreType:        core.StringPtr("in_place"),
        RestorePointInTime: core.StringPtr(restorePointInTime),
        TargetResourceCrn:  core.StringPtr(targetBucketCrn),
    }
    restoreResponse, _, err := rcClient.CreateRestore(restoreOptions)
    if err != nil {
        log.Fatalf("Failed to initiate restore: %v", err)
    }
    fmt.Printf(restoreResponse)
}

列表恢复

func main() {
    // Setup authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // List restores
    listOptions := &resourceconfigurationv1.ListRestoresOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
    }
    restoreListResponse, _, err := rcClient.ListRestores(listOptions)
    if err != nil {
        log.Fatalf("Failed to list restore operations: %v", err)
    }
    fmt.Printf(restoreListResponse)
}

获取恢复详情

func main() {
    // Setup authenticator
    authenticator := &core.IamAuthenticator{
        ApiKey: apiKey,
    }
    // Initialize Resource Configuration client
    rcClient, err := resourceconfigurationv1.NewResourceConfigurationV1(&resourceconfigurationv1.ResourceConfigurationV1Options{
        Authenticator: authenticator,
    })
    if err != nil {
        log.Fatalf("Failed to create RC client: %v", err)
    }
    // Get specific restore
    restoreGetOptions := &resourceconfigurationv1.GetRestoreOptions{
        BackupVaultName: core.StringPtr(backupVaultName),
        RestoreID:       core.StringPtr(restoreId),
    }
    restoreDetails, _, err := rcClient.GetRestore(restoreGetOptions)
    if err != nil {
        log.Fatalf("Failed to get restore details: %v", err)
    }
    fmt.Printf("Restore details: %+v\n", restoreDetails)
}

创建一个启用对象锁的新 Cloud Object Storage 桶

func createBucket(bucketName string, client *s3.S3) {
    createBucketInput := new(s3.CreateBucketInput)
    createBucketInput.Bucket = aws.String(bucketName)
    createBucketInput.ObjectLockEnabledForBucket = aws.Bool(true)
    _, e := client.CreateBucket(createBucketInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Bucket Created !!! ")
    }
}

将对象锁配置与合规模式放在 Cloud Object Storage bucket 上

func objectLockConfiguration(bucketName string, client *s3.S3) {
    // Putting default retenion on the COS bucket.
    putObjectLockConfigurationInput := &s3.PutObjectLockConfigurationInput{
        Bucket: aws.String(bucketName),
        ObjectLockConfiguration: &s3.ObjectLockConfiguration{
            ObjectLockEnabled: aws.String(s3.ObjectLockEnabledEnabled),
            Rule: &s3.ObjectLockRule{
                DefaultRetention: &s3.DefaultRetention{
                    Mode: aws.String("COMPLIANCE"),
                    Days: aws.Int64(1),
                },
            },
        },
    }
    _, e := client.PutObjectLockConfiguration(putObjectLockConfigurationInput)
}

将对象锁配置与治理模式放在 Cloud Object Storage bucket 上

func objectLockConfigurationwithGovernanceMode(bucketName string, client *s3.S3) {
    // Putting default retenion on the COS bucket.
    putObjectLockConfigurationInput := &s3.PutObjectLockConfigurationInput{
        Bucket: aws.String(bucketName),
        ObjectLockConfiguration: &s3.ObjectLockConfiguration{
            ObjectLockEnabled: aws.String(s3.ObjectLockEnabledEnabled),
            Rule: &s3.ObjectLockRule{
                DefaultRetention: &s3.DefaultRetention{
                    Mode: aws.String("GOVERNANCE"),
                    Days: aws.Int64(1),
                },
            },
        },
    }
    _, e := client.PutObjectLockConfiguration(putObjectLockConfigurationInput)
}

获取 Cloud Object Storage 桶上的对象锁配置

func objectLockConfigurationwithGovernanceMode(bucketName string, client *s3.S3) {
    // Reading the objectlock configuration set on the bucket.
    getObjectLockConfigurationInput := new(s3.GetObjectLockConfigurationInput)
    getObjectLockConfigurationInput.Bucket = aws.String(bucketName)
    response, e := client.GetObjectLockConfiguration(getObjectLockConfigurationInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock Configuration =>", response.ObjectLockConfiguration)
    }
}

将具有治理模式的对象上传到 Cloud Object Storage bucket

func uploadObjectWithGovernanceMode(bucketName string, client *s3.S3, fileName string, fileContent string) {
    retention_date := time.Now().Local().Add(time.Second * 5)
    putInput := &s3.PutObjectInput{
        Bucket:                    aws.String(bucketName),
        Key:                       aws.String(fileName),
        Body:                      bytes.NewReader([]byte(fileContent)),
        ObjectLockMode:            aws.String("GOVERNANCE"),
        ObjectLockRetainUntilDate: aws.Time(retention_date),
    }
    _, e := client.PutObject(putInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Uploaded!!! ")
    }
}

为对象启用对象锁保留与合规模式

func objectLockRetention(bucketName string, client *s3.S3, keyName string) {
    // Put objectlock retenion on the  object uploaded to the bucket.
    retention_date := time.Now().Local().Add(time.Second * 5)
    putObjectRetentionInput := &s3.PutObjectRetentionInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(keyName),
        Retention: &s3.ObjectLockRetention{
            Mode:            aws.String("COMPLIANCE"),
            RetainUntilDate: aws.Time(retention_date),
        },
    }
    _, e := client.PutObjectRetention(putObjectRetentionInput)
}

为对象启用对象锁保留与治理模式

func objectLockRetentionWithGovernanceMode(bucketName string, client *s3.S3, keyName string) {
    // Put objectlock retenion on the  object uploaded to the bucket.
    retention_date := time.Now().Local().Add(time.Second * 5)
    putObjectRetentionInput := &s3.PutObjectRetentionInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(keyName),
        Retention: &s3.ObjectLockRetention{
            Mode:            aws.String("GOVERNANCE"),
            RetainUntilDate: aws.Time(retention_date),
        },
    }
    _, e := client.PutObjectRetention(putObjectRetentionInput)
}

获取对象锁保留

func objectLockRetentionWithGovernanceMode(bucketName string, client *s3.S3, keyName string) {
    // Get objectlock retention of the above object.
    getObjectRetentionInput := new(s3.GetObjectRetentionInput)
    getObjectRetentionInput.Bucket = aws.String(bucketName)
    getObjectRetentionInput.Key = aws.String(keyName)
    response, e := client.GetObjectRetention(getObjectRetentionInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock Retention =>", response.Retention)
    }
}

设置对象锁定法律保留

func objectLocklegalHold(bucketName string, client *s3.S3, keyName string) {
    // Setting the objectlock legal-hold status to ON.
    putObjectlegalHoldInput := &s3.PutObjectlegalHoldInput{
        Bucket: aws.String(bucketName),
        Key:    aws.String(keyName),
        legalHold: &s3.ObjectLocklegalHold{
            Status: aws.String("ON"),
        },
    }
    _, e := client.PutObjectlegalHold(putObjectlegalHoldInput)
}

获取对象锁定法律保留

func objectLocklegalHold(bucketName string, client *s3.S3, keyName string) {
    // Get objectlock retention of the above object.
    getObjectlegalHoldInput := new(s3.GetObjectlegalHoldInput)
    getObjectlegalHoldInput.Bucket = aws.String(bucketName)
    getObjectlegalHoldInput.Key = aws.String(keyName)
    response, e := client.GetObjectlegalHold(getObjectlegalHoldInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Lock legal-hold =>", response.legalHold)
    }
}

删除使用旁路治理的对象锁治理模式的对象

func deleteObjectWithBypassGovernance(bucketName string, client *s3.S3, fileName string) {
    deleteObjectInput := new(s3.DeleteObjectInput)
    deleteObjectInput.Bucket = aws.String(bucketName)
    deleteObjectInput.Key = aws.String("foo")
    deleteObjectInput.BypassGovernanceRetention = aws.Bool(true)
    _, e := client.DeleteObject(deleteObjectInput)
    if e != nil {
        fmt.Println(e)
    } else {
        fmt.Println("Object Deleted")
    }
}

后续步骤

如果您还没有,请参阅 Go API 文档中的详细类和方法文档。