package yandex import ( "context" "fmt" "io" "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/s3" ) type s3Config struct { Region string AccessKey string SecretKey string BucketName string Endpoint string } type yandexS3Service struct { client *s3.Client uploader *manager.Uploader bucketName string endpoint string } func newYandexS3Service(cfg s3Config) (*yandexS3Service, error) { if cfg.Region == "" || cfg.AccessKey == "" || cfg.SecretKey == "" || cfg.BucketName == "" { return nil, fmt.Errorf("missing required S3 configuration parameters") } // Создаем конфигурацию awsCfg, err := config.LoadDefaultConfig(context.Background(), config.WithRegion(cfg.Region), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, "")), ) if err != nil { return nil, fmt.Errorf("failed to load AWS config: %w", err) } // Создаем клиент S3 var client *s3.Client if cfg.Endpoint != "" { // Кастомный endpoint (например, для MinIO) client = s3.NewFromConfig(awsCfg, func(o *s3.Options) { o.BaseEndpoint = aws.String(cfg.Endpoint) o.UsePathStyle = true }) } else { // Стандартный AWS S3 client = s3.NewFromConfig(awsCfg) } uploader := manager.NewUploader(client) return &yandexS3Service{ client: client, uploader: uploader, bucketName: cfg.BucketName, endpoint: cfg.Endpoint, }, nil } func (s *yandexS3Service) uploadFile(file io.Reader, fileName string) error { _, err := s.uploader.Upload(context.Background(), &s3.PutObjectInput{ Bucket: aws.String(s.bucketName), Key: aws.String(fileName), Body: file, }) if err != nil { return fmt.Errorf("failed to upload file to S3: %w", err) } return nil } func (s *yandexS3Service) fileUrl(fileName string) string { endpoint := strings.TrimRight(s.endpoint, "/") return fmt.Sprintf("%s/%s/%s", endpoint, s.bucketName, fileName) }