64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package blob
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
)
|
|
|
|
type S3Store struct {
|
|
client *minio.Client
|
|
bucket string
|
|
}
|
|
|
|
func NewS3Store(endpoint, accessKey, secretKey, bucket string, useSSL bool) (*S3Store, error) {
|
|
client, err := minio.New(endpoint, &minio.Options{
|
|
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
|
Secure: useSSL,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("creating S3 client: %w", err)
|
|
}
|
|
|
|
return &S3Store{client: client, bucket: bucket}, nil
|
|
}
|
|
|
|
func (s *S3Store) EnsureBucket(ctx context.Context) error {
|
|
exists, err := s.client.BucketExists(ctx, s.bucket)
|
|
if err != nil {
|
|
return fmt.Errorf("checking bucket: %w", err)
|
|
}
|
|
if !exists {
|
|
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{}); err != nil {
|
|
return fmt.Errorf("creating bucket: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *S3Store) Put(ctx context.Context, key string, reader io.Reader, size int64) error {
|
|
_, err := s.client.PutObject(ctx, s.bucket, key, reader, size, minio.PutObjectOptions{})
|
|
if err != nil {
|
|
return fmt.Errorf("uploading object %s: %w", key, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *S3Store) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
|
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("getting object %s: %w", key, err)
|
|
}
|
|
return obj, nil
|
|
}
|
|
|
|
func (s *S3Store) Delete(ctx context.Context, key string) error {
|
|
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
|
return fmt.Errorf("deleting object %s: %w", key, err)
|
|
}
|
|
return nil
|
|
}
|