Utilizzo di Go V2
L'SDK IBM Cloud® Object Storage per Go v2 fornisce funzionalità per sfruttare al meglio IBM Cloud Object Storage.
L'SDK IBM Cloud Object Storage per Go v2 è completo, con molte caratteristiche e funzionalità che vanno oltre lo scopo di questa guida. Per la documentazione dettagliata delle classi e dei metodi, vedere la documentazione di riferimento dell'API Go. Il codice sorgente è disponibile nel repository GitHub.
Cosa c'è di nuovo in v2
L'SDK IBM Cloud Object Storage per Go v2 è una versione modernizzata che si basa sull'architettura dell'SDK AWS v2, apportando miglioramenti significativi:
- Architettura modulare: Nuovo spazio dei nomi
github.com/IBM/ibm-cos-sdk-go-v2con un'organizzazione più pulita - Supporto contestuale migliorato: Supporto nativo di
context.Contextper tutte le operazioni API, che consente una migliore gestione dei timeout e delle cancellazioni - Gestione moderna degli errori: Tipi di errore strutturati, più facili da ispezionare e da gestire programmaticamente
- Supporto per i moduli Go: Supporto di prima classe per i moduli Go con versioning semantico
Per gli sviluppatori che migrano da v1, consultare la Guida alla migrazione.
Ottenimento dell'SDK
Il modo più semplice per utilizzare l'SDK Go IBM Cloud Object Storage v2 è quello di usare i moduli Go per gestire le dipendenze. Se non si ha familiarità con i moduli Go, è possibile iniziare a lavorare utilizzando la guida Go Modules in 5-Minutes.
Prerequisiti
- Go 1.23 o successivo- L'SDK richiede una versione minima di Go 1.23 o più recente
- Un'istanza di IBM Cloud Object Storage
- Una chiave API da IBM Cloud Identity and Access Management con almeno i permessi di
Writer - L'ID dell'istanza di IBM Cloud Object Storage con cui si sta lavorando
- Punto finale di acquisizione dei gettoni
- Endpoint del servizio
Questi valori possono essere trovati nella console IBM Cloud generando una "credenziale di servizio".
Installazione dell'SDK
Utilizza go get per richiamare l'SDK per aggiungerlo al tuo spazio di lavoro GOPATH o alle dipendenze di modulo Go del progetto. L'SDK richiede una versione minima di 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
Per aggiornare l'SDK, utilizzare go get -u per recuperare l'ultima versione dell'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
Importa pacchetti
Dopo che hai installato l'SDK, dovrai importare i pacchetti di cui hai bisogno nelle tue applicazioni Go per utilizzare l'SDK, come mostrato nel seguente esempio:
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"
)
Riferimenti SDK
Corsi di base
- s3.Client- Cliente principale per interagire con IBM Cloud Object Storage
- s3.NewFromConfig- Crea un nuovo client S3 dalla configurazione
Credenziali
- ibmiam.NewStaticCredentials- IBM Fornitore di credenziali IAM per l'autenticazione con chiave API
- config.WithCredentialsProvider- Opzione di configurazione per impostare il fornitore di credenziali
Configurazione
- config.LoadDefaultConfig- Carica la configurazione dell'SDK con le opzioni specificate
- config.WithRegion- Imposta la regione AWS per il client
- config.WithEndpoint- Imposta il punto finale del servizio URL
Creare un cliente e reperire le credenziali del servizio
Per stabilire una connessione a IBM Cloud Object Storage, un client viene creato e configurato fornendo le informazioni delle credenziali (chiave API e ID istanza del servizio). Questi valori possono anche essere derivati automaticamente da un file di credenziali o dalle variabili di ambiente.
Le credenziali possono essere trovate creando una credenziale del servizio o tramite la CLI.
Utilizzo dell'autenticazione IAM di IBM
L'esempio seguente mostra come creare un client utilizzando l'autenticazione IAM di IBM con una chiave 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)
Le variabili richieste sono:
apiKey- La vostra chiave API IBM Cloud con le autorizzazioni appropriateserviceInstanceID- Il CRN (Cloud Resource Name) dell'istanza IBM Cloud Object StorageauthEndpoint- L'endpoint del token IAM di IBM (tipicamentehttps://iam.cloud.ibm.com/identity/token)serviceEndpoint- Il punto finale URL per la regione del secchio IBM Cloud Object Storageregion- La regione in cui si trova il secchio
Esempi di codice
Gli esempi seguenti presuppongono che sia già stato creato un client come mostrato nella sezione precedente.
Creazione di un bucket
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)
Elenco dei secchi disponibili
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,
)
}
Elenco dei bucket con informazioni estese
IBM Cloud Object Storage fornisce un'operazione di elencazione estesa che restituisce informazioni aggiuntive sul secchio:
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)
}
Recupero della posizione di un bucket
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,
)
Eliminazione di un bucket
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)
Un bucket deve essere vuoto prima di poter essere eliminato.
Caricamento di un oggetto in un bucket
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))
Scaricare un oggetto da un bucket
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))
Elencare gli oggetti in un secchio
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))
Copiare un oggetto
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))
Eliminazione di un oggetto
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)
Eliminazione di più oggetti
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),
)
}
}
Ottenere i metadati dell'oggetto (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)
}
}
Utilizzo di caricamenti in più parti
Per gli oggetti di grandi dimensioni, il caricamento multiparte consente di migliorare il throughput e di riprendere il caricamento. Ogni parte deve essere di almeno 5 MB (tranne l'ultima).
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))
Elenco dei caricamenti multiparte
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)
}
Impostazione della configurazione del ciclo di vita del bucket
I criteri di archiviazione consentono di passare automaticamente gli oggetti alle classi di archiviazione dopo un determinato periodo di tempo:
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)
Ottenere la configurazione del ciclo di vita del bucket
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),
)
}
}
Abilitazione del versioning del bucket
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)
Elenco delle versioni degli oggetti
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)
}
Impostazione della configurazione di 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)
Impostazione dell'etichettatura degli oggetti
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)
Ottenere i tag degli oggetti
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))
}
Ripristino di un oggetto archiviato
Gli oggetti delle classi di archiviazione devono essere ripristinati prima di potervi accedere:
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 supporta l'archiviazione accelerata con tempi di ripristino di 2 ore o 12 ore, a seconda del livello selezionato.
Impostazione della configurazione della protezione del secchio
IBM Cloud Object Storage supporta Immutable Object Storage per evitare che gli oggetti vengano modificati o cancellati:
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")
Ottenere la configurazione della protezione del secchio
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))
Aggiunta di una presa legale a un oggetto
Le detenzioni legali impediscono la cancellazione o la modifica di un oggetto, indipendentemente dai periodi di conservazione:
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")
Il bucket deve avere un blocco dell'oggetto abilitato per utilizzare le prese legali.
Elenco delle detenzioni legali di un oggetto
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)
}
}
Eliminazione di un blocco legale da un oggetto
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)
Impostazione della conservazione degli oggetti
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)
Ottenere la conservazione degli oggetti
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)
Passi successivi
- Per informazioni dettagliate su tutti i metodi e i tipi disponibili, consultare la documentazione di riferimento dell'API Go
- Esplorare il repository GitHub per ulteriori esempi e codice sorgente
- Leggete la Guida alla migrazione se state effettuando l'aggiornamento da v1
- Consultate il sito IBM Cloud Object Storage documentazione per le caratteristiche e le best practice specifiche del servizio
- Per aiuto e supporto:
- Porre domande su Stack Overflow con i tag
ibmeobject-storage - Aprire un problema su GitHub
- Contattare l'assistenza IBM Cloud
- Porre domande su Stack Overflow con i tag