feat: Automatic creation of buckets and setting expiration rules
This commit is contained in:
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user