Trabajo con S3 y almacenamiento en la nube en Go: biblioteca minio-go

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Biblioteca minio-go para trabajar con S3 y almacenamiento en la nube en Go



En el desarrollo moderno, cada vez surge más la necesidad de integrarse con almacenamiento en la nube compatible con el protocolo Amazon S3 (Simple Storage Service). Ya sea AWS S3, Yandex.Cloud, DigitalOcean Spaces, MinIO o cualquier otro servicio compatible con S3, el lenguaje Go ofrece una solución elegante y eficiente: la biblioteca minio-go.



Minio-go es el cliente oficial de Go para la API de Amazon S3, desarrollado por la empresa MinIO. Proporciona un conjunto completo de funciones para gestionar buckets y objetos, admite carga/descarga en streaming, cifrado, versionado y muchas otras capacidades de S3. La biblioteca es totalmente compatible con AWS S3 y cualquier otro almacenamiento compatible con S3.



Instalación



La instalación de la biblioteca se realiza de forma estándar mediante go get:



go get github.com/minio/minio-go/v7


Conexión y configuración del cliente



Para comenzar, es necesario crear un cliente especificando el endpoint, access key y secret key. Ejemplo de conexión a MinIO (local o en la nube):



package main

import ( "context" "log" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials")

func main() { ctx := context.Background() // Parámetros de conexión endpoint := "play.min.io" // o tu endpoint accessKeyID := "Q3AM3UQ867SPQQA43P2F" secretAccessKey := "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" useSSL := true

// Creación del cliente client, err := minio.New(endpoint, &minio.Options{ Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), Secure: useSSL, }) if err != nil { log.Fatalf("Error al crear el cliente: %v", err) }

log.Println("Conexión al almacenamiento S3 establecida")}


Trabajo con buckets



Un bucket es el directorio raíz en el almacenamiento S3. Veamos las operaciones principales:



Creación de un bucket



bucketName := "my-go-bucket"location := "us-east-1"

err = client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{ Region: location,})if err != nil { log.Printf("No se pudo crear el bucket: %v", err)} else { log.Printf("Bucket '%s' creado exitosamente", bucketName)}


Verificar si un bucket existe



exists, err := client.BucketExists(ctx, bucketName)if err != nil {    log.Fatalf("Error al verificar el bucket: %v", err)}if exists {    log.Printf("El bucket '%s' existe", bucketName)}


Listar todos los buckets



buckets, err := client.ListBuckets(ctx)if err != nil {    log.Fatalf("Error al obtener la lista de buckets: %v", err)}for _, bucket := range buckets {    log.Printf("Bucket: %s, creado: %s", bucket.Name, bucket.CreationDate)}


Carga de archivos (upload)



Minio-go admite la carga de archivos desde el sistema de archivos local, desde io.Reader y desde un buffer en memoria. Ejemplo de carga de un archivo:



objectName := "example.txt"filePath := "/path/to/local/file.txt"contentType := "text/plain"

// Carga del archivon, err := client.FPutObject(ctx, bucketName, objectName, filePath, minio.PutObjectOptions{ ContentType: contentType,})if err != nil { log.Fatalf("Error al cargar el archivo: %v", err)}log.Printf("Archivo '%s' cargado, tamaño: %d bytes", objectName, n.Size)


Carga desde memoria (bytes/reader)



import "strings"

data := strings.NewReader("¡Hola, almacenamiento S3!")objectName := "hello.txt"

n, err := client.PutObject(ctx, bucketName, objectName, data, int64(data.Len()), minio.PutObjectOptions{ ContentType: "text/plain",})if err != nil { log.Fatalf("Error al cargar datos: %v", err)}log.Printf("Cargados %d bytes", n.Size)

Recommendations