Utilizar Go V2

El SDK de IBM Cloud® Object Storage para Go v2 proporciona funciones para sacar el máximo partido a IBM Cloud Object Storage.

El SDK de IBM Cloud Object Storage para Go v2 es muy completo, con muchas funciones y capacidades que exceden el alcance de esta guía. Para obtener documentación detallada sobre clases y métodos, consulte la documentación de referencia de la API Go. Encontrará el código fuente en el repositorio GitHub.

Novedades en v2

El SDK IBM Cloud Object Storage para Go v2 es una versión modernizada que se basa en la arquitectura del SDK AWS v2, aportando mejoras significativas:

  • Arquitectura modular: Nuevo espacio de nombres github.com/IBM/ibm-cos-sdk-go-v2 con una organización más limpia
  • Soporte de contexto mejorado: Compatibilidad nativa con context.Context para todas las operaciones de la API, lo que permite gestionar mejor los tiempos de espera y las cancelaciones
  • Gestión moderna de errores: Tipos de error estructurados que son más fáciles de inspeccionar y manejar programáticamente
  • Compatibilidad con módulos Go: Soporte de primera clase para módulos Go con versionado semántico

Para los desarrolladores que migran desde v1, consulte la Guía de migración.

Obtención del SDK

La forma más sencilla de utilizar el SDK Go de IBM Cloud Object Storage v2 es utilizar módulos Go para gestionar las dependencias. Si no estás familiarizado con los módulos Go, puedes ponerte manos a la obra con la guía Módulos Go en 5 minutos.

Requisitos previos

  • Go 1.23 o posterior- El SDK requiere una versión mínima de Go 1.23 o posterior
  • Una instancia de IBM Cloud Object Storage
  • Una clave API de IBM Cloud Identity and Access Management con al menos Writer permisos
  • ID de la instancia de IBM Cloud Object Storage con la que está trabajando
  • Punto final de adquisición de tokens
  • Punto final de servicio

Estos valores pueden consultarse en la consola IBM Cloud generando una "credencial de servicio".

Instalación del SDK

Utilice go get para recuperar el SDK para añadirlo al espacio de trabajo GOPATH o a las dependencias de módulo Go del proyecto. El SDK requiere una versión mínima de 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

Para actualizar el SDK, utilice go get -u para recuperar la última versión del 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

Importación de paquetes

Después de instalar el SDK, tendrá que importar los paquetes que necesite en las aplicaciones Go para utilizar el SDK, tal como se muestra en el ejemplo siguiente:

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

Referencias SDK

Clases principales

  • s3.Client- Cliente principal para interactuar con IBM Cloud Object Storage
  • s3.NewFromConfig- Crea un nuevo cliente S3 a partir de la configuración

Credenciales

  • ibmiam.NewStaticCredentials- IBM Proveedor de credenciales IAM para la autenticación de claves API
  • config.WithCredentialsProvider- Opción de configuración para establecer el proveedor de credenciales

Configuración

  • config.LoadDefaultConfig- Carga la configuración del SDK con las opciones especificadas
  • config.WithRegion- Establece la región AWS para el cliente
  • config.WithEndpoint- Establece el punto final del servicio URL

Crear un cliente y obtener credenciales de servicio

Para conectarse a IBM Cloud Object Storage, se crea y se configura un cliente proporcionando información de credenciales (clave de API e ID de instancia de servicio). Estos valores también se pueden tomar automáticamente de un archivo de credenciales o de variables de entorno.

Puede encontrar las credenciales creando una credencial de servicio o a través de la CLI.

Utilización de la autenticación IAM en IBM

El siguiente ejemplo muestra cómo crear un cliente utilizando la autenticación IAM de IBM con una clave 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)

Las variables necesarias son:

  • apiKey- Su clave API IBM Cloud con los permisos adecuados
  • serviceInstanceID- El CRN (Cloud Resource Name) de su instancia IBM Cloud Object Storage
  • authEndpoint- El punto final de token IAM de IBM (normalmente https://iam.cloud.ibm.com/identity/token)
  • serviceEndpoint- El punto final URL para la región de su cubo IBM Cloud Object Storage
  • region- La región donde se encuentra su cubo

Ejemplos de código

Los siguientes ejemplos suponen que ya ha creado un cliente como se muestra en la sección anterior.

Creación de un grupo

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)

Listado de cubos disponibles

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

Listado de cubos con información ampliada

IBM Cloud Object Storage proporciona una operación de listado ampliada que devuelve información adicional sobre los cubos:

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

Recuperar la ubicación de un cubo

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

Supresión de un grupo

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 cubo debe estar vacío para poder ser eliminado.

Cargar un objeto en un cubo

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

Descargar un objeto de un cubo

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

Listado de objetos en un grupo

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

Copiar un objeto

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

Supresión de un objeto

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)

Supresión de varios objetos

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

Obtener metadatos de objetos (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)
    }
}

Utilización de cargas de varias partes

En el caso de objetos grandes, la carga multiparte ofrece un mayor rendimiento y la posibilidad de reanudar la carga. Cada parte debe ocupar al menos 5 MB (excepto la última parte).

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

Listado de cargas 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)
}

Configuración del ciclo de vida de un cubo

Las políticas de archivo permiten pasar automáticamente objetos a clases de almacenamiento de archivo tras un periodo de tiempo determinado:

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)

Obtener la configuración del ciclo de vida de un cubo

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

Activar el versionado de cubos

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)

Listado de versiones de objetos

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

Configuración de 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)

Establecer el etiquetado de objetos

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)

Obtener etiquetas de objetos

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

Restaurar un objeto archivado

Los objetos de las clases de almacenamiento de archivo deben restaurarse antes de poder acceder a ellos:

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 admite el archivado acelerado con tiempos de restauración de 2 o 12 horas, según el nivel seleccionado.

Configuración de la protección del cubo

IBM Cloud Object Storage soporta Inmutable Object Storage para evitar que los objetos sean modificados o borrados:

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

Obtención de la configuración de protección del cubo

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

Fijar la retención de objetos

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)

Conseguir la retención de objetos

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)

Próximos pasos