Files

93 lines
2.6 KiB
Go

package storage
import (
"context"
"time"
"cloudnest/internal/pkg/logger"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// PresignDuration is the default duration for pre-signed URLs.
// PresignDuration 是预签名 URL 的默认有效期。
var PresignDuration = 24 * time.Hour
// MinioClient provides MinIO object storage operations.
// MinioClient 提供 MinIO 对象存储操作。
//
// This struct wraps the MinIO client and provides methods for storage operations.
//
// 此结构体封装了 MinIO 客户端,并提供了存储操作的方法。
type MinioClient struct {
Client *minio.Client
}
// NewMinioClient creates a new MinIO client.
// NewMinioClient 创建一个新的 MinIO 客户端。
//
// Parameters:
// - endpoint: The MinIO server endpoint (host:port).
// - accessKey: The MinIO access key.
// - secretKey: The MinIO secret key.
// - useSSL: Whether to use SSL/TLS for connections.
//
// Returns:
// - *MinioClient: A pointer to the new MinioClient instance.
// - error: An error if the connection fails.
//
// 参数:
// - endpoint: MinIO 服务器端点(host:port)。
// - accessKey: MinIO 访问密钥。
// - secretKey: MinIO 秘密密钥。
// - useSSL: 是否使用 SSL/TLS 连接。
//
// 返回值:
// - *MinioClient: 新创建的 MinioClient 实例指针。
// - error: 如果连接失败则返回错误。
func NewMinioClient(endpoint, accessKey, secretKey string, useSSL bool) (*MinioClient, error) {
client, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
Secure: useSSL,
})
if err != nil {
return nil, err
}
logger.Info("minio connected")
return &MinioClient{Client: client}, nil
}
// EnsureBucket creates the bucket if it doesn't exist.
// EnsureBucket 如果桶不存在则创建桶。
//
// Parameters:
// - bucketName: The name of the bucket to ensure.
//
// Returns:
// - error: An error if the operation fails.
//
// Note:
// - This method is idempotent - it can be called safely even if the bucket exists.
//
// 参数:
// - bucketName: 要确保存在的桶名称。
//
// 返回值:
// - error: 如果操作失败则返回错误。
//
// 注意:
// - 此方法是幂等的 - 即使桶已存在也可以安全调用。
func (c *MinioClient) EnsureBucket(bucketName string) error {
exists, err := c.Client.BucketExists(context.Background(), bucketName)
if err != nil {
return err
}
if !exists {
if err := c.Client.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{}); err != nil {
return err
}
logger.Info("bucket created", "bucket", bucketName)
}
return nil
}