forked from mtusi2026/mtusi2026lab4
67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package s3
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
)
|
|
|
|
func NewClient() (*minio.Client, string, error) {
|
|
endpoint := os.Getenv("S3_ENDPOINT")
|
|
accessKey := os.Getenv("S3_ACCESS_KEY")
|
|
secretKey := os.Getenv("S3_SECRET_KEY")
|
|
bucket := os.Getenv("S3_BUCKET")
|
|
|
|
if endpoint == "" || accessKey == "" || secretKey == "" || bucket == "" {
|
|
return nil, "", errors.New("S3_ENDPOINT, S3_ACCESS_KEY, S3_SECRET_KEY, S3_BUCKET must be set")
|
|
}
|
|
|
|
endpoint = strings.TrimPrefix(endpoint, "http://")
|
|
endpoint = strings.TrimPrefix(endpoint, "https://")
|
|
|
|
client, err := minio.New(endpoint, &minio.Options{
|
|
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
|
Secure: false,
|
|
})
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
|
|
return client, bucket, nil
|
|
}
|
|
|
|
func EnsureBucket(ctx context.Context, client *minio.Client, bucket string) error {
|
|
exists, err := client.BucketExists(ctx, bucket)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !exists {
|
|
return client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{})
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func UploadFile(ctx context.Context, client *minio.Client, bucket, key string, data io.Reader, size int64, contentType string) error {
|
|
_, err := client.PutObject(ctx, bucket, key, data, size, minio.PutObjectOptions{
|
|
ContentType: contentType,
|
|
})
|
|
return err
|
|
}
|
|
|
|
func DownloadFile(ctx context.Context, client *minio.Client, bucket, key string) (io.ReadCloser, error) {
|
|
obj, err := client.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return obj, nil
|
|
}
|
|
|
|
func DeleteFile(ctx context.Context, client *minio.Client, bucket, key string) error {
|
|
return client.RemoveObject(ctx, bucket, key, minio.RemoveObjectOptions{})
|
|
}
|