guestbooky/src/Guestbooky-backup/internal/uploader/uploader.go
Felipe Cotti 1ed22ba9a6
Some checks failed
CI/CD / build-backup-job (push) Has been cancelled
CI/CD / build-and-test-backend (push) Has been cancelled
Don't hide errors from the uploader.
2025-01-27 02:48:38 -03:00

74 lines
1.7 KiB
Go

package uploader
import (
"errors"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
type S3Client struct {
bucketName string
s3Client *s3.S3
}
func Upload(compactedFile string) error {
fmt.Println(
"Uploading", compactedFile, "to storage",
)
s3Client, err := createS3Client()
if err != nil {
return errors.New("failed to create S3 client: " + err.Error())
}
file, err := os.Open(compactedFile)
if err != nil {
return errors.New("failed to open file: " + err.Error())
}
defer file.Close()
uploader := s3manager.NewUploaderWithClient(s3Client.s3Client)
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: &s3Client.bucketName,
Key: &compactedFile,
Body: file,
})
if err != nil {
return errors.New("failed to upload file: " + err.Error())
}
return nil
}
func createS3Client() (*S3Client, error) {
keyId := os.Getenv("BACKUP_S3_ACCESS_ID")
applicationKey := os.Getenv("BACKUP_S3_SECRET_ID")
bucketName := os.Getenv("BACKUP_S3_KEY_NAME")
endpoint := os.Getenv("BACKUP_S3_ENDPOINT")
region := os.Getenv("BACKUP_S3_REGION")
s3Config := &aws.Config{
Credentials: credentials.NewStaticCredentials(keyId, applicationKey, ""),
Endpoint: &endpoint,
Region: &region,
}
awsSession, err := session.NewSession(s3Config)
if err != nil {
return nil, errors.New("failed to create S3 session: " + err.Error())
}
s3Client := s3.New(awsSession)
return &S3Client{
bucketName: bucketName,
s3Client: s3Client,
}, nil
}