Add S3 integration for uploading files to dynamic buckets

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-07-19 23:16:10 -06:00
parent 3a40c818ef
commit 1cf5617111
2 changed files with 57 additions and 1 deletions

View File

@@ -1,15 +1,21 @@
package integration
import "github.com/eduardolat/pgbackweb/internal/integration/pgdump"
import (
"github.com/eduardolat/pgbackweb/internal/integration/pgdump"
"github.com/eduardolat/pgbackweb/internal/integration/s3"
)
type Integration struct {
PGDumpClient *pgdump.Client
S3Client *s3.Client
}
func New() *Integration {
pgdumpClient := pgdump.New()
s3Client := s3.New()
return &Integration{
PGDumpClient: pgdumpClient,
S3Client: s3Client,
}
}

View File

@@ -0,0 +1,50 @@
package s3
import (
"bytes"
"fmt"
"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/eduardolat/pgbackweb/internal/util/strutil"
)
type Client struct{}
func New() *Client {
return &Client{}
}
func (c *Client) Upload(
accessKey, secretKey, region, endpoint, bucketName, key string,
fileContent []byte,
) (string, error) {
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials(accessKey, secretKey, ""),
Region: aws.String(region),
Endpoint: aws.String(endpoint),
S3ForcePathStyle: aws.Bool(true),
})
if err != nil {
return "", fmt.Errorf("failed to create aws session: %w", err)
}
s3Client := s3.New(sess)
reader := bytes.NewReader(fileContent)
key = strutil.RemoveLeadingSlash(key)
contentType := strutil.GetContentTypeFromFileName(key)
_, err = s3Client.PutObject(&s3.PutObjectInput{
Bucket: aws.String(bucketName),
Key: aws.String(key),
Body: aws.ReadSeekCloser(reader),
ContentType: aws.String(contentType),
})
if err != nil {
return "", fmt.Errorf("failed to upload file to S3: %w", err)
}
return fmt.Sprintf("s3://%s/%s", bucketName, key), nil
}