package amazon
import (
"bytes"
"context"
"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/service/s3"
)
type amazonClient struct {
ctx *s3.Client
bucket string
}
func NewAmazonClient(bucketUrl, accessKey, secretAccessKey, workingBucket string) *amazonClient {
r2Resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: bucketUrl,
}, nil
})
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithEndpointResolverWithOptions(r2Resolver),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretAccessKey, "")),
)
if err != nil {
panic(err.Error())
}
return &amazonClient{
ctx: s3.NewFromConfig(cfg),
bucket: workingBucket,
}
}
func (a *amazonClient) GetObject(key string) ([]byte, error) {
output, err := a.ctx.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: aws.String(a.bucket),
Key: aws.String(key),
})
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
buf.ReadFrom(output.Body)
return buf.Bytes(), nil
}
func (a *amazonClient) PutObject(key string, data []byte) error {
_, err := a.ctx.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(a.bucket),
Key: aws.String(key),
Body: bytes.NewReader(data),
})
return err
}