74 lines
2.0 KiB
Go
74 lines
2.0 KiB
Go
package minio
|
|
|
|
import (
|
|
minioclient "Yimaru-Backend/internal/pkgs/minio"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"path"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type Service struct {
|
|
client *minioclient.Client
|
|
logger *zap.Logger
|
|
}
|
|
|
|
func NewService(client *minioclient.Client, logger *zap.Logger) *Service {
|
|
return &Service{
|
|
client: client,
|
|
logger: logger,
|
|
}
|
|
}
|
|
|
|
// Init ensures the bucket exists. Should be called once at startup.
|
|
func (s *Service) Init(ctx context.Context) error {
|
|
return s.client.EnsureBucket(ctx)
|
|
}
|
|
|
|
// UploadResult holds the result of an upload operation.
|
|
type UploadResult struct {
|
|
ObjectKey string
|
|
}
|
|
|
|
// Upload stores a file in MinIO under the given subdirectory.
|
|
// It generates a unique filename and returns the object key.
|
|
func (s *Service) Upload(ctx context.Context, subDir string, filename string, reader io.Reader, fileSize int64, contentType string) (*UploadResult, error) {
|
|
ext := path.Ext(filename)
|
|
objectKey := subDir + "/" + uuid.New().String() + ext
|
|
|
|
s.logger.Info("Uploading file to MinIO",
|
|
zap.String("object_key", objectKey),
|
|
zap.Int64("size", fileSize),
|
|
zap.String("content_type", contentType),
|
|
)
|
|
|
|
if err := s.client.UploadFile(ctx, objectKey, reader, fileSize, contentType); err != nil {
|
|
s.logger.Error("Failed to upload file to MinIO",
|
|
zap.String("object_key", objectKey),
|
|
zap.Error(err),
|
|
)
|
|
return nil, fmt.Errorf("failed to upload to MinIO: %w", err)
|
|
}
|
|
|
|
s.logger.Info("File uploaded to MinIO successfully", zap.String("object_key", objectKey))
|
|
|
|
return &UploadResult{
|
|
ObjectKey: objectKey,
|
|
}, nil
|
|
}
|
|
|
|
// GetURL returns a presigned URL for the given object key.
|
|
func (s *Service) GetURL(ctx context.Context, objectKey string, expiry time.Duration) (string, error) {
|
|
return s.client.GetFileURL(ctx, objectKey, expiry)
|
|
}
|
|
|
|
// Delete removes a file from MinIO.
|
|
func (s *Service) Delete(ctx context.Context, objectKey string) error {
|
|
s.logger.Info("Deleting file from MinIO", zap.String("object_key", objectKey))
|
|
return s.client.DeleteFile(ctx, objectKey)
|
|
}
|