-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket.go
More file actions
75 lines (65 loc) · 1.8 KB
/
bucket.go
File metadata and controls
75 lines (65 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package database
import (
"context"
"fmt"
"log"
"mime/multipart"
"os"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func InitBucket() *minio.Client {
endpoint := os.Getenv("BUCKET_ENDPOINT")
accessKeyID := os.Getenv("BUCKET_ACCESS_KEY")
secretAccessKey := os.Getenv("BUCKET_SECRET_KEY")
useSSL := false
minioClient, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: useSSL,
})
if err != nil {
log.Fatalln("Failed to initialize minio client:", err)
}
log.Println("Successfully connected to Minio")
return minioClient
}
func UploadFile(client *minio.Client, file *multipart.FileHeader) (string, error) {
ctx := context.Background()
bucketName := "user-profile"
publicDomain := os.Getenv("BUCKET_PUBLIC_DOMAIN")
if publicDomain == "" {
publicDomain = "http://localhost:8334"
}
src, err := file.Open()
if err != nil {
return "", err
}
defer func(src multipart.File) {
err := src.Close()
if err != nil {
}
}(src)
exists, err := client.BucketExists(ctx, bucketName)
if err != nil {
return "", err
}
if !exists {
err := client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})
if err != nil {
return "", fmt.Errorf("failed to create bucket %s: %v", bucketName, err)
}
log.Println("Successfully created bucket:", bucketName)
}
objectName := fmt.Sprintf("file_%d_%s", time.Now().Unix(), file.Filename)
contentType := file.Header.Get("Content-Type")
info, err := client.PutObject(ctx, bucketName, objectName, src, file.Size, minio.PutObjectOptions{
ContentType: contentType,
})
if err != nil {
return "", err
}
log.Println("Successfully uploaded file:", info)
fileURL := fmt.Sprintf("%s/%s/%s", publicDomain, bucketName, objectName)
return fileURL, nil
}