使用 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 金鑰及服務實例 ID),來建立及配置用戶端。 這些值也可以自動從 credentials 檔案或環境變數中取得。

可以藉由建立服務認證,或透過 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 的 Trusted Profile 認證

現在您可以建立一個用戶端,透過使用服務 ID 和受信任的設定檔來驗證 IBM Cloud Object Storage。 Trusted Profiles 可讓 IBM Cloud 身份存取帳戶中的資源,而無需直接成為該帳戶的成員。 透過將服務 ID 與受信任的設定檔相關聯,您可以安全地授予其資源存取權,包括位於不同 IBM Cloud 帳戶的資源。 如需詳細資訊,請參閱 IBM Cloud 有關建立 服務 ID 的可信設定檔 的說明文件。

開始之前

  1. 在來源帳戶中建立服務 ID
    • 在服務 ID 中,建立 API 金鑰並註記 API 金鑰值。
  2. 在目標帳戶中建立受信任的設定檔,並與來源帳戶的服務 ID 相關聯。 請參閱 在主控台中使用服務 ID 建立信任目標帳戶是包含要存取的資源的帳戶。
  3. 為受信任的設定檔指定適當的存取權限

使用服務 ID 和受信任的設定檔進行驗證

設定完成後,使用 Go SDK 建立用戶端,使用服務 ID 和 Trusted Profile 進行驗證。

  1. 使用 Trusted Profile 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. 使用 Trusted Profile name 設定用戶端組態:

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

列出桶中的項目(List Objects 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 服務的實例 ID
  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"
         }]
     }]
 }

Immutable Object Storage

使用者可以設定具有不變 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"
   }
 }

建立代管的靜態網站

這項作業需要許可權,因為通常只允許儲存區擁有者配置儲存區來管理靜態網站。 這些參數決定網站訪客的預設字尾,以及這裡所包含用來完成範例的選用錯誤文件。

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 文件中提供的詳細類和方法文件。