囲碁を使う V2
IBM Cloud® Object Storage SDK for Go v2 は、 IBM Cloud Object Storage を最大限に活用するための機能を提供します。
IBM Cloud Object Storage SDK for Go v2 は包括的なもので、このガイドの範囲を超える多くの特徴と機能を備えています。 クラスとメソッドの詳細については、 Go APIリファレンス・ドキュメントを 参照してください。 ソース・コードは、GitHub リポジトリーにあります。
新着情報 v2
IBM Cloud Object Storage SDK for Go v2 は、 AWS SDK v2 アーキテクチャ上に構築された最新バージョンで、大幅な改良が加えられている:
- モジュラーアーキテクチャ :新しい名前空間
github.com/IBM/ibm-cos-sdk-go-v2 - コンテキスト・サポートの強化 :すべてのAPI操作で
context.Contextをネイティブサポートし、タイムアウトとキャンセルの処理を改善 - 最新のエラー処理 :構造化されたエラー・タイプにより、検査やプログラムによる処理が容易になる
- Go モジュールのサポート :セマンティック・バージョニングによるGoモジュールのファーストクラス・サポート
v1 から移行する開発者については、 移行ガイドを 参照してください。
SDK の取得
IBM Cloud Object Storage Go SDK v2 を使う最も簡単な方法は、Goモジュールを使って依存関係を管理することです。 Goモジュールに慣れていない場合は、「 5分でわかるGoモジュール 」ガイドを使用して、すぐに使い始めることができます。
前提条件
- Go 1.23 またはそれ以降- SDK には最低バージョンの Go 1.23 またはそれ以降が必要です
- のインスタンスである。 IBM Cloud Object Storage
- APIキーは IBM Cloud Identity and Access Management 少なくとも
Writerのパーミッションを持つ - IBM Cloud Object Storage のインスタンスのID
- トークン獲得エンドポイント
- サービス・エンドポイント
これらの値は、 「サービス・クレデンシャル」を生成 することにより、 IBM Cloud コンソールで見つけることができる。
SDK のインストール
go get を使用して SDK を取得し、GOPATH ワークスペースに追加するか、プロジェクトの Go モジュール依存関係に追加します。 SDKには、最小バージョンのGo 1.23 が必要です。
go get github.com/IBM/ibm-cos-sdk-go-v2/config
go get github.com/IBM/ibm-cos-sdk-go-v2/service/s3
go get github.com/IBM/ibm-cos-sdk-go-v2/credentials/ibmiam
SDKをアップデートするには、 go get -u :
go get -u github.com/IBM/ibm-cos-sdk-go-v2/config
go get -u github.com/IBM/ibm-cos-sdk-go-v2/service/s3
go get -u github.com/IBM/ibm-cos-sdk-go-v2/credentials/ibmiam
パッケージのインポート
SDK のインストールが完了したら、以下の例に示すように、SDK を使用するために必要なパッケージを Go アプリケーションにインポートする必要があります。
import (
"context"
"github.com/IBM/ibm-cos-sdk-go-v2/aws"
"github.com/IBM/ibm-cos-sdk-go-v2/config"
"github.com/IBM/ibm-cos-sdk-go-v2/credentials/ibmiam"
"github.com/IBM/ibm-cos-sdk-go-v2/service/s3"
"github.com/IBM/ibm-cos-sdk-go-v2/service/s3/types"
)
SDKリファレンス
コア・クラス
- s3.Client- 主な取引先 IBM Cloud Object Storage
- s3.NewFromConfig- コンフィギュレーションから新しい S3 クライアントを作成する
資格情報
- ibmiam.NewStaticCredentials- IBM APIキー認証用のIAM資格情報プロバイダ
- config.WithCredentialsProvider- 資格情報プロバイダを設定するための設定オプション
構成
- config.LoadDefaultConfig- 指定されたオプションでSDK設定をロードします
- config.WithRegion- クライアントの AWS 地域を設定する
- config.WithEndpoint- サービスのエンドポイントを設定する URL
クライアントの作成とサービス資格の調達
IBM Cloud Object Storage に接続するために、資格情報 (API キーとサービス・インスタンス ID) を指定することによりクライアントが作成および構成されます。 これらの値は、資格情報ファイルまたは環境変数から自動的に入手することもできます。
資格情報は、サービス資格情報を作成するか、CLI を介して見つけることができます。
IBM IAM認証の使用
以下の例では、 IBM IAM認証にAPIキーを使用してクライアントを作成する方法を示します:
// IBM COS credentials
apiKey := "<API_KEY>"
serviceInstanceID := "<RESOURCE_INSTANCE_ID>"
authEndpoint := "https://iam.cloud.ibm.com/identity/token"
serviceEndpoint := "https://s3.us-south.cloud-object-storage.appdomain.cloud"
region := "us-south"
// Load configuration with IBM IAM credentials
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithCredentialsProvider(
ibmiam.NewStaticCredentials(authEndpoint, apiKey, serviceInstanceID),
),
config.WithRegion(region),
config.WithEndpoint(serviceEndpoint),
)
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
// Create S3 client
client := s3.NewFromConfig(cfg)
必要な変数は以下の通り:
apiKey- 適切なパーミッションを持つ IBM Cloud API キーserviceInstanceID- IBM Cloud Object Storage インスタンスの CRN (クラウド・リソース名)authEndpoint- IBM IAM トークンのエンドポイント (通常はhttps://iam.cloud.ibm.com/identity/token)serviceEndpoint- IBM Cloud Object Storage バケツのリージョンのエンドポイント URLregion- あなたのバケットがある地域
コード例
以下の例は、前のセクションで示したように、すでにクライアントを作成していることを前提にしています。
バケットの作成
bucketName := "my-new-bucket"
input := &s3.CreateBucketInput{
Bucket: aws.String(bucketName),
}
_, err = client.CreateBucket(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to create bucket: %v", err)
}
fmt.Printf("Bucket '%s' created successfully\n", bucketName)
利用可能なバケツのリスト
result, err := client.ListBuckets(context.TODO(), &s3.ListBucketsInput{})
if err != nil {
log.Fatalf("Failed to list buckets: %v", err)
}
fmt.Println("Buckets:")
for _, bucket := range result.Buckets {
fmt.Printf(" - %s (created: %v)\n",
aws.ToString(bucket.Name),
bucket.CreationDate,
)
}
拡張情報を持つバケツのリスト
IBM Cloud Object Storage は、追加のバケツ情報を返す拡張リスト操作を提供します:
input := &s3.ListBucketsExtendedInput{
IBMServiceInstanceId: aws.String(serviceInstanceID),
Prefix: aws.String("my-bucket-prefix"),
MaxKeys: aws.Int32(100),
}
result, err := client.ListBucketsExtended(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to list buckets: %v", err)
}
fmt.Println("Extended Bucket Information:")
for _, bucket := range result.Buckets {
fmt.Printf(" Bucket: %s\n", aws.ToString(bucket.Name))
fmt.Printf(" Location: %s\n", aws.ToString(bucket.LocationConstraint))
fmt.Printf(" Created: %v\n", bucket.CreationDate)
}
バケツの位置を取得する
bucketName := "my-bucket"
result, err := client.GetBucketLocation(context.TODO(), &s3.GetBucketLocationInput{
Bucket: aws.String(bucketName),
})
if err != nil {
log.Fatalf("Failed to get bucket location: %v", err)
}
fmt.Printf("Bucket '%s' is located in: %s\n",
bucketName,
result.LocationConstraint,
)
バケットの削除
bucketName := "my-bucket-to-delete"
_, err = client.DeleteBucket(context.TODO(), &s3.DeleteBucketInput{
Bucket: aws.String(bucketName),
})
if err != nil {
log.Fatalf("Failed to delete bucket: %v", err)
}
fmt.Printf("Bucket '%s' deleted successfully\n", bucketName)
バケツを削除するには、バケツが空でなければなりません。
バケツへのオブジェクトのアップロード
bucketName := "my-bucket"
objectKey := "my-object.txt"
content := "Hello, IBM Cloud Object Storage!"
input := &s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Body: strings.NewReader(content),
}
result, err := client.PutObject(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to upload object: %v", err)
}
fmt.Printf("Object '%s' uploaded successfully\n", objectKey)
fmt.Printf("ETag: %s\n", aws.ToString(result.ETag))
バケツからオブジェクトをダウンロードする
bucketName := "my-bucket"
objectKey := "my-object.txt"
result, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Failed to download object: %v", err)
}
defer result.Body.Close()
// Read the object content
data, err := io.ReadAll(result.Body)
if err != nil {
log.Fatalf("Failed to read object data: %v", err)
}
fmt.Printf("Object '%s' downloaded successfully\n", objectKey)
fmt.Printf("Content-Type: %s\n", aws.ToString(result.ContentType))
fmt.Printf("Content-Length: %d bytes\n", result.ContentLength)
fmt.Printf("Content:\n%s\n", string(data))
バケット内のオブジェクトのリスト表示
bucketName := "my-bucket"
input := &s3.ListObjectsV2Input{
Bucket: aws.String(bucketName),
MaxKeys: aws.Int32(1000),
}
result, err := client.ListObjectsV2(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to list objects: %v", err)
}
fmt.Printf("Objects in bucket '%s':\n", bucketName)
for _, object := range result.Contents {
fmt.Printf(" - %s (size: %d bytes, modified: %v)\n",
aws.ToString(object.Key),
object.Size,
object.LastModified,
)
}
fmt.Printf("\nTotal objects: %d\n", len(result.Contents))
オブジェクトのコピー
sourceBucket := "source-bucket"
sourceKey := "source-object.txt"
destinationBucket := "destination-bucket"
destinationKey := "destination-object.txt"
// CopySource format: /source-bucket/source-key
copySource := fmt.Sprintf("/%s/%s", sourceBucket, sourceKey)
input := &s3.CopyObjectInput{
Bucket: aws.String(destinationBucket),
Key: aws.String(destinationKey),
CopySource: aws.String(copySource),
}
result, err := client.CopyObject(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to copy object: %v", err)
}
fmt.Printf("Object copied successfully\n")
fmt.Printf("Copy ETag: %s\n", aws.ToString(result.CopyObjectResult.ETag))
オブジェクトの削除
bucketName := "my-bucket"
objectKey := "object-to-delete.txt"
_, err = client.DeleteObject(context.TODO(), &s3.DeleteObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Failed to delete object: %v", err)
}
fmt.Printf("Object '%s' deleted successfully\n", objectKey)
複数のオブジェクトの削除
bucketName := "my-bucket"
objectsToDelete := []string{
"object1.txt",
"object2.txt",
"object3.txt",
}
// Build delete request
var objects []types.ObjectIdentifier
for _, key := range objectsToDelete {
objects = append(objects, types.ObjectIdentifier{
Key: aws.String(key),
})
}
input := &s3.DeleteObjectsInput{
Bucket: aws.String(bucketName),
Delete: &types.Delete{
Objects: objects,
Quiet: aws.Bool(false),
},
}
result, err := client.DeleteObjects(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to delete objects: %v", err)
}
fmt.Printf("Successfully deleted %d objects\n", len(result.Deleted))
for _, deleted := range result.Deleted {
fmt.Printf(" - %s\n", aws.ToString(deleted.Key))
}
if len(result.Errors) > 0 {
fmt.Printf("\nFailed to delete %d objects:\n", len(result.Errors))
for _, err := range result.Errors {
fmt.Printf(" - %s: %s\n",
aws.ToString(err.Key),
aws.ToString(err.Message),
)
}
}
オブジェクトのメタデータを取得する(HEAD)
bucketName := "my-bucket"
objectKey := "my-object.txt"
result, err := client.HeadObject(context.TODO(), &s3.HeadObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Failed to get object metadata: %v", err)
}
fmt.Printf("Object Metadata for '%s':\n", objectKey)
fmt.Printf(" Content-Type: %s\n", aws.ToString(result.ContentType))
fmt.Printf(" Content-Length: %d bytes\n", result.ContentLength)
fmt.Printf(" ETag: %s\n", aws.ToString(result.ETag))
fmt.Printf(" Last-Modified: %v\n", result.LastModified)
if len(result.Metadata) > 0 {
fmt.Println(" Custom Metadata:")
for key, value := range result.Metadata {
fmt.Printf(" %s: %s\n", key, value)
}
}
複数パーツ・アップロードの使用
大きなオブジェクトの場合、マルチパートアップロードはスループットを向上させ、アップロードを再開する機能を提供する。 各パートは5MB以上でなければなりません(最後のパートを除く)。
bucketName := "my-bucket"
objectKey := "large-object.dat"
// Step 1: Initiate multipart upload
createResp, err := client.CreateMultipartUpload(context.TODO(),
&s3.CreateMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
},
)
if err != nil {
log.Fatalf("Failed to initiate multipart upload: %v", err)
}
uploadID := aws.ToString(createResp.UploadId)
fmt.Printf("Multipart upload initiated with ID: %s\n", uploadID)
// Step 2: Upload parts (minimum 5MB per part except last)
var completedParts []types.CompletedPart
minPartSize := 5 * 1024 * 1024 // 5MB
// Create sample parts
parts := []string{
strings.Repeat("A", minPartSize),
strings.Repeat("B", minPartSize),
}
for i, partData := range parts {
partNumber := int32(i + 1)
uploadResp, err := client.UploadPart(context.TODO(), &s3.UploadPartInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
PartNumber: aws.Int32(partNumber),
UploadId: aws.String(uploadID),
Body: strings.NewReader(partData),
})
if err != nil {
// Abort multipart upload on error
client.AbortMultipartUpload(context.TODO(), &s3.AbortMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadID),
})
log.Fatalf("Failed to upload part %d: %v", partNumber, err)
}
completedParts = append(completedParts, types.CompletedPart{
ETag: uploadResp.ETag,
PartNumber: aws.Int32(partNumber),
})
fmt.Printf("Part %d uploaded (ETag: %s)\n", partNumber, aws.ToString(uploadResp.ETag))
}
// Step 3: Complete multipart upload
completeResp, err := client.CompleteMultipartUpload(context.TODO(),
&s3.CompleteMultipartUploadInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
UploadId: aws.String(uploadID),
MultipartUpload: &types.CompletedMultipartUpload{
Parts: completedParts,
},
},
)
if err != nil {
log.Fatalf("Failed to complete multipart upload: %v", err)
}
fmt.Printf("Multipart upload completed successfully\n")
fmt.Printf("Location: %s\n", aws.ToString(completeResp.Location))
fmt.Printf("ETag: %s\n", aws.ToString(completeResp.ETag))
マルチパート・アップロードの一覧表示
bucketName := "my-bucket"
result, err := client.ListMultipartUploads(context.TODO(),
&s3.ListMultipartUploadsInput{
Bucket: aws.String(bucketName),
},
)
if err != nil {
log.Fatalf("Failed to list multipart uploads: %v", err)
}
fmt.Printf("In-progress multipart uploads in bucket '%s':\n", bucketName)
for _, upload := range result.Uploads {
fmt.Printf(" Key: %s\n", aws.ToString(upload.Key))
fmt.Printf(" Upload ID: %s\n", aws.ToString(upload.UploadId))
fmt.Printf(" Initiated: %v\n", upload.Initiated)
}
バケツのライフサイクル設定の設定
アーカイブ・ポリシーでは、指定した期間が経過したオブジェクトを自動的にアーカイブ・ストレージ・クラスに移行させることができます:
bucketName := "my-bucket"
// Configure lifecycle rule to archive objects after 90 days
input := &s3.PutBucketLifecycleConfigurationInput{
Bucket: aws.String(bucketName),
LifecycleConfiguration: &types.BucketLifecycleConfiguration{
Rules: []types.LifecycleRule{
{
ID: aws.String("archive-rule"),
Status: types.ExpirationStatusEnabled,
Filter: &types.LifecycleRuleFilterMemberPrefix{
Value: "documents/",
},
Transitions: []types.Transition{
{
Days: aws.Int32(90),
StorageClass: types.TransitionStorageClassGlacier,
},
},
},
},
},
}
_, err = client.PutBucketLifecycleConfiguration(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to set lifecycle configuration: %v", err)
}
fmt.Printf("Lifecycle configuration set for bucket '%s'\n", bucketName)
バケツのライフサイクル設定の取得
bucketName := "my-bucket"
result, err := client.GetBucketLifecycleConfiguration(context.TODO(),
&s3.GetBucketLifecycleConfigurationInput{
Bucket: aws.String(bucketName),
},
)
if err != nil {
log.Fatalf("Failed to get lifecycle configuration: %v", err)
}
fmt.Printf("Lifecycle rules for bucket '%s':\n", bucketName)
for _, rule := range result.Rules {
fmt.Printf(" Rule ID: %s\n", aws.ToString(rule.ID))
fmt.Printf(" Status: %s\n", rule.Status)
for _, transition := range rule.Transitions {
fmt.Printf(" Transition to %s after %d days\n",
transition.StorageClass,
aws.ToInt32(transition.Days),
)
}
}
バケットのバージョニングを有効にする
bucketName := "my-bucket"
// Enable versioning
_, err = client.PutBucketVersioning(context.TODO(), &s3.PutBucketVersioningInput{
Bucket: aws.String(bucketName),
VersioningConfiguration: &types.VersioningConfiguration{
Status: types.BucketVersioningStatusEnabled,
},
})
if err != nil {
log.Fatalf("Failed to enable versioning: %v", err)
}
fmt.Printf("Versioning enabled for bucket '%s'\n", bucketName)
オブジェクト・バージョンのリスト
bucketName := "my-bucket"
result, err := client.ListObjectVersions(context.TODO(),
&s3.ListObjectVersionsInput{
Bucket: aws.String(bucketName),
},
)
if err != nil {
log.Fatalf("Failed to list object versions: %v", err)
}
fmt.Printf("Object versions in bucket '%s':\n", bucketName)
for _, version := range result.Versions {
fmt.Printf(" Key: %s\n", aws.ToString(version.Key))
fmt.Printf(" Version ID: %s\n", aws.ToString(version.VersionId))
fmt.Printf(" Is Latest: %t\n", aws.ToBool(version.IsLatest))
fmt.Printf(" Last Modified: %v\n", version.LastModified)
}
CORS コンフィギュレーションの設定
bucketName := "my-bucket"
// Set CORS configuration
input := &s3.PutBucketCorsInput{
Bucket: aws.String(bucketName),
CORSConfiguration: &types.CORSConfiguration{
CORSRules: []types.CORSRule{
{
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"GET", "PUT", "POST", "DELETE"},
AllowedOrigins: []string{"https://example.com"},
ExposeHeaders: []string{"ETag"},
MaxAgeSeconds: aws.Int32(3000),
},
},
},
}
_, err = client.PutBucketCors(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to set CORS configuration: %v", err)
}
fmt.Printf("CORS configuration set for bucket '%s'\n", bucketName)
オブジェクト・タグの設定
bucketName := "my-bucket"
objectKey := "my-object.txt"
// Set object tags
input := &s3.PutObjectTaggingInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Tagging: &types.Tagging{
TagSet: []types.Tag{
{
Key: aws.String("Department"),
Value: aws.String("Finance"),
},
{
Key: aws.String("Project"),
Value: aws.String("Q4-2024"),
},
{
Key: aws.String("Classification"),
Value: aws.String("Confidential"),
},
},
},
}
_, err = client.PutObjectTagging(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to set object tags: %v", err)
}
fmt.Printf("Tags set for object '%s'\n", objectKey)
オブジェクトタグの取得
bucketName := "my-bucket"
objectKey := "my-object.txt"
result, err := client.GetObjectTagging(context.TODO(), &s3.GetObjectTaggingInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Failed to get object tags: %v", err)
}
fmt.Printf("Tags for object '%s':\n", objectKey)
for _, tag := range result.TagSet {
fmt.Printf(" %s: %s\n", aws.ToString(tag.Key), aws.ToString(tag.Value))
}
アーカイブされたオブジェクトのリストア
アーカイブ・ストレージ・クラスのオブジェクトは、アクセスする前にリストアする必要があります:
bucketName := "my-bucket"
objectKey := "archived-object.txt"
// Restore object with accelerated retrieval (2 hours)
input := &s3.RestoreObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
RestoreRequest: &types.RestoreRequest{
Days: aws.Int32(7), // Number of days to keep restored copy
GlacierJobParameters: &types.GlacierJobParameters{
Tier: types.TierAccelerated, // Accelerated (2 hours) or Standard (12 hours)
},
},
}
_, err = client.RestoreObject(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to restore object: %v", err)
}
fmt.Printf("Restore request submitted for object '%s'\n", objectKey)
fmt.Println("The object will be available for download in approximately 2 hours")
IBM Cloud Object Storage は、選択した階層に応じて、2時間または12時間のリストア時間を持つ加速アーカイブをサポートしています。
バケット保護設定の設定
IBM Cloud Object Storage は、オブジェクトが変更されたり削除されたりするのを防ぐために、Immutable Object Storage をサポートしています:
bucketName := "my-protected-bucket"
// Set protection configuration with default retention period
input := &s3.PutBucketProtectionConfigurationInput{
Bucket: aws.String(bucketName),
ProtectionConfiguration: &types.ProtectionConfiguration{
Status: types.BucketProtectionStatusRetention,
MinimumRetention: &types.BucketProtectionMinimumRetention{Days: aws.Int32(90)},
MaximumRetention: &types.BucketProtectionMaximumRetention{Days: aws.Int32(365)},
DefaultRetention: &types.BucketProtectionDefaultRetention{Days: aws.Int32(120)},
EnablePermanentRetention: aws.Bool(false),
},
}
_, err = client.PutBucketProtectionConfiguration(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to set protection configuration: %v", err)
}
fmt.Printf("Protection configuration set for bucket '%s'\n", bucketName)
fmt.Println("Objects will be protected with a default retention of 120 days")
バケット保護設定の取得
bucketName := "my-protected-bucket"
result, err := client.GetBucketProtectionConfiguration(context.TODO(),
&s3.GetBucketProtectionConfigurationInput{
Bucket: aws.String(bucketName),
},
)
if err != nil {
log.Fatalf("Failed to get protection configuration: %v", err)
}
fmt.Printf("Protection configuration for bucket '%s':\n", bucketName)
fmt.Printf(" Status: %s\n", result.ProtectionConfiguration.Status)
fmt.Printf(" Minimum Retention: %d days\n",
aws.ToInt32(result.ProtectionConfiguration.MinimumRetention.Days))
fmt.Printf(" Maximum Retention: %d days\n",
aws.ToInt32(result.ProtectionConfiguration.MaximumRetention.Days))
fmt.Printf(" Default Retention: %d days\n",
aws.ToInt32(result.ProtectionConfiguration.DefaultRetention.Days))
オブジェクトにリーガル・ホールドを追加する
リーガル・ホールドは、保存期間に関係なく、オブジェクトを削除または変更することを防ぎます:
bucketName := "my-protected-bucket"
objectKey := "important-document.pdf"
legalHoldID := "legal-case-2024-001"
// Add legal hold to the object
_, err = client.AddLegalHold(context.TODO(), &s3.AddLegalHoldInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
RetentionLegalHoldId: aws.String(legalHoldID),
})
if err != nil {
log.Fatalf("Failed to add legal hold: %v", err)
}
fmt.Printf("Legal hold '%s' added to object '%s'\n", legalHoldID, objectKey)
fmt.Println("The object cannot be deleted or modified until the legal hold is removed")
合法的なホールドを使用するためには、Bucket が Object Lock を有効にしていなければなりません。
オブジェクトの合法的なホールドをリストアップする
bucketName := "my-protected-bucket"
objectKey := "important-document.pdf"
// List legal holds
result, err := client.ListLegalHolds(context.TODO(), &s3.ListLegalHoldsInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Failed to list legal holds: %v", err)
}
fmt.Printf("Legal holds on object '%s':\n", objectKey)
if len(result.LegalHolds) == 0 {
fmt.Println(" No legal holds")
} else {
for _, hold := range result.LegalHolds {
fmt.Printf(" - ID: %s\n", aws.ToString(hold.ID))
fmt.Printf(" Date: %v\n", hold.Date)
}
}
オブジェクトからリーガル・ホールドを削除する
bucketName := "my-protected-bucket"
objectKey := "important-document.pdf"
legalHoldID := "legal-case-2024-001"
// Delete legal hold
_, err = client.DeleteLegalHold(context.TODO(), &s3.DeleteLegalHoldInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
RetentionLegalHoldId: aws.String(legalHoldID),
})
if err != nil {
log.Fatalf("Failed to delete legal hold: %v", err)
}
fmt.Printf("Legal hold '%s' removed from object '%s'\n", legalHoldID, objectKey)
オブジェクト保持の設定
bucketName := "my-protected-bucket"
objectKey := "important-document.pdf"
// Set retention until a specific date
retainUntilDate := time.Now().AddDate(0, 6, 0) // 6 months from now
input := &s3.PutObjectRetentionInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
Retention: &types.ObjectLockRetention{
Mode: types.ObjectLockRetentionModeCompliance,
RetainUntilDate: aws.Time(retainUntilDate),
},
}
_, err = client.PutObjectRetention(context.TODO(), input)
if err != nil {
log.Fatalf("Failed to set object retention: %v", err)
}
fmt.Printf("Retention set for object '%s' until %v\n", objectKey, retainUntilDate)
オブジェクトの保持を得る
bucketName := "my-protected-bucket"
objectKey := "important-document.pdf"
result, err := client.GetObjectRetention(context.TODO(), &s3.GetObjectRetentionInput{
Bucket: aws.String(bucketName),
Key: aws.String(objectKey),
})
if err != nil {
log.Fatalf("Failed to get object retention: %v", err)
}
fmt.Printf("Retention for object '%s':\n", objectKey)
fmt.Printf(" Mode: %s\n", result.Retention.Mode)
fmt.Printf(" Retain Until: %v\n", result.Retention.RetainUntilDate)
次のステップ
- 利用可能なすべてのメソッドと型の詳細については、 Go API のリファレンス・ドキュメントを 参照してください
- より多くの例とソースコードについては、 GitHub リポジトリを 探索してください
- からアップグレードする場合は、 移行ガイドを お読みください。 v1
- サービス固有の機能やベストプラクティスについては、 IBM Cloud Object Storage のドキュメントを ご覧ください
- ヘルプとサポート
- Stack Overflow でタグ
ibmを付けて質問する。object-storage - 次のページでissueを開く GitHub
- IBM Cloud サポート
- Stack Overflow でタグ