From e15ee90a62b8de6ba183f82e271deafa187eee74 Mon Sep 17 00:00:00 2001 From: Nikolai Papin Date: Mon, 28 Jul 2025 01:41:01 +0300 Subject: [PATCH] feat: Automatic creation of buckets and setting expiration rules --- backend/internal/minioClient/buckets.go | 38 +++++++++++++++++++++---- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/backend/internal/minioClient/buckets.go b/backend/internal/minioClient/buckets.go index be052bb..4beed7d 100644 --- a/backend/internal/minioClient/buckets.go +++ b/backend/internal/minioClient/buckets.go @@ -19,29 +19,55 @@ package minioclient import ( "context" + "slices" "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/lifecycle" ) -var buckets map[string]string +var Buckets map[string]string func setupBuckets(client *minio.Client) { - buckets = map[string]string{ + Buckets = map[string]string{ "avatars": "avatars", "images": "images", + "uploads": "uploads", } ctx := context.Background() - for _, value := range buckets { - - if bucketExists, err := client.BucketExists(ctx, value); err != nil { + var newBuckets []string + for key, value := range Buckets { + bucketExists, err := client.BucketExists(ctx, value); if err != nil { panic("Failure to check if bucket '" + value + "' exists: " + err.Error()) - } else if !bucketExists { + } + + if !bucketExists { err := client.MakeBucket(ctx, value, minio.MakeBucketOptions{}); if err != nil { panic("Failure to create bucket '" + value + "': " + err.Error()) } + newBuckets = append(newBuckets, key) } + } + if slices.Contains(newBuckets, "uploads") { + uploadsCfg := lifecycle.NewConfiguration() + uploadsCfg.Rules = []lifecycle.Rule{ + { + ID: "expire-uploads", + Status: "enabled", + Expiration: lifecycle.Expiration{Days: 1}, + }, + } + + err := client.SetBucketLifecycle(ctx, Buckets["uploads"], uploadsCfg); if err != nil { + errRm := client.RemoveBucket(ctx, Buckets["uploads"]) + + if errRm != nil { + panic("Failed to set lifecycle configuration for the uploads bucket: '" + err.Error() + "' and then failed to delete it: " + errRm.Error()) + } + + panic("Failed to set lifecycle configuration for the uploads bucket: " + err.Error()) + } } }