66 lines
2.2 KiB
Go
66 lines
2.2 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/aws/aws-sdk-go-v2/aws"
|
|
awsconfig "github.com/aws/aws-sdk-go-v2/config"
|
|
"github.com/aws/aws-sdk-go-v2/credentials"
|
|
"github.com/aws/aws-sdk-go-v2/service/s3"
|
|
"tss-rocks-be/internal/config"
|
|
)
|
|
|
|
// NewStorage creates a new storage instance based on the configuration
|
|
func NewStorage(ctx context.Context, cfg *config.StorageConfig) (Storage, error) {
|
|
switch cfg.Type {
|
|
case "local":
|
|
return NewLocalStorage(cfg.Local.RootDir)
|
|
case "s3":
|
|
// Load AWS configuration
|
|
var s3Client *s3.Client
|
|
|
|
if cfg.S3.Endpoint != "" {
|
|
// Custom endpoint (e.g., MinIO)
|
|
customResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
|
|
return aws.Endpoint{
|
|
URL: cfg.S3.Endpoint,
|
|
}, nil
|
|
})
|
|
|
|
awsCfg, err := awsconfig.LoadDefaultConfig(ctx,
|
|
awsconfig.WithRegion(cfg.S3.Region),
|
|
awsconfig.WithEndpointResolverWithOptions(customResolver),
|
|
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
|
|
cfg.S3.AccessKeyID,
|
|
cfg.S3.SecretAccessKey,
|
|
"",
|
|
)),
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to load AWS SDK config: %w", err)
|
|
}
|
|
|
|
s3Client = s3.NewFromConfig(awsCfg)
|
|
} else {
|
|
// Standard AWS S3
|
|
awsCfg, err := awsconfig.LoadDefaultConfig(ctx,
|
|
awsconfig.WithRegion(cfg.S3.Region),
|
|
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
|
|
cfg.S3.AccessKeyID,
|
|
cfg.S3.SecretAccessKey,
|
|
"",
|
|
)),
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to load AWS SDK config: %w", err)
|
|
}
|
|
|
|
s3Client = s3.NewFromConfig(awsCfg)
|
|
}
|
|
|
|
return NewS3Storage(s3Client, cfg.S3.Bucket, cfg.S3.CustomURL, cfg.S3.ProxyS3), nil
|
|
default:
|
|
return nil, fmt.Errorf("unsupported storage type: %s", cfg.Type)
|
|
}
|
|
}
|