99 lines
2.3 KiB
Go
99 lines
2.3 KiB
Go
package s3
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
|
|
"high-loud-apps-labs/internal/domain"
|
|
)
|
|
|
|
type Config struct {
|
|
Endpoint string
|
|
Bucket string
|
|
AccessKey string
|
|
SecretKey string
|
|
UseSSL bool
|
|
Region string
|
|
}
|
|
|
|
type MinioStorage struct {
|
|
client *minio.Client
|
|
bucket string
|
|
}
|
|
|
|
func New(ctx context.Context, cfg Config) (*MinioStorage, error) {
|
|
client, err := minio.New(cfg.Endpoint, &minio.Options{
|
|
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
|
Secure: cfg.UseSSL,
|
|
Region: cfg.Region,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
exists, err := client.BucketExists(ctx, cfg.Bucket)
|
|
if err != nil {
|
|
return nil, mapError(err)
|
|
}
|
|
if !exists {
|
|
return nil, &domain.UnavailableError{Reason: "s3 bucket отсутствует"}
|
|
}
|
|
|
|
return &MinioStorage{client: client, bucket: cfg.Bucket}, nil
|
|
}
|
|
|
|
func (s *MinioStorage) Ping(ctx context.Context) error {
|
|
_, err := s.client.BucketExists(ctx, s.bucket)
|
|
return mapError(err)
|
|
}
|
|
|
|
func (s *MinioStorage) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
|
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{
|
|
ContentType: contentType,
|
|
})
|
|
return mapError(err)
|
|
}
|
|
|
|
func (s *MinioStorage) Get(ctx context.Context, key string) (io.ReadCloser, int64, string, error) {
|
|
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
return nil, 0, "", mapError(err)
|
|
}
|
|
|
|
stat, err := obj.Stat()
|
|
if err != nil {
|
|
_ = obj.Close()
|
|
return nil, 0, "", mapError(err)
|
|
}
|
|
|
|
return obj, stat.Size, stat.ContentType, nil
|
|
}
|
|
|
|
func (s *MinioStorage) Delete(ctx context.Context, key string) error {
|
|
err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
|
|
return mapError(err)
|
|
}
|
|
|
|
func (s *MinioStorage) List(ctx context.Context, prefix string) ([]domain.ObjectInfo, error) {
|
|
out := make([]domain.ObjectInfo, 0)
|
|
for obj := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{
|
|
Prefix: prefix,
|
|
Recursive: true,
|
|
}) {
|
|
if obj.Err != nil {
|
|
return nil, mapError(obj.Err)
|
|
}
|
|
out = append(out, domain.ObjectInfo{
|
|
Key: obj.Key,
|
|
LastModified: obj.LastModified,
|
|
Size: obj.Size,
|
|
})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
var _ domain.ObjectStorage = (*MinioStorage)(nil)
|