mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-02-28 09:09:05 -06:00
Add S3 integration for uploading files to dynamic buckets
This commit is contained in:
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
50
internal/integration/s3/s3.go
Normal file
50
internal/integration/s3/s3.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user