Go 사용 V2
Go용 IBM Cloud® Object Storage SDK v2 는 IBM Cloud Object Storage 를 최대한 활용할 수 있는 기능을 제공합니다.
Go용 IBM Cloud Object Storage SDK( v2 )는 이 가이드의 범위를 넘어서는 많은 기능과 기능을 갖춘 포괄적인 제품입니다. 자세한 클래스 및 메서드 설명서는 Go API 참조 문서를 참조하세요. 소스 코드는 GitHub 저장소에서 찾을 수 있습니다.
새로운 기능 v2
Go용 IBM Cloud Object Storage SDK 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 에서 최신 버전의 SDK를 검색하세요:
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 인증 사용
다음 예는 API 키로 IBM IAM 인증을 사용하여 클라이언트를 만드는 방법을 보여줍니다:
// 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 버킷의 지역에 대한 URL 엔드포인트region- 버킷이 위치한 지역
코드 예제
다음 예제에서는 이전 섹션에 표시된 대로 이미 클라이언트를 만들었다고 가정합니다.
버킷 작성
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 는 객체가 수정되거나 삭제되지 않도록 불변( 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")
법적 보류를 사용하려면 버킷에 객체 잠금이 활성화되어 있어야 합니다.
객체에 대한 법적 보류 목록
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 설명서를 확인하세요
- 도움과 지원을 요청하세요:
- 스택 오버플로에서
ibm및object-storage - 다음에서 이슈를 엽니다 GitHub
- 문의 IBM Cloud 지원
- 스택 오버플로에서