/
r2.go
63 lines (54 loc) · 1.48 KB
/
r2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"bytes"
"context"
"fmt"
"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"
)
// R2 is a struct describing r2 cloudflare storage bucket.
type R2 struct {
Bucket string
client *s3.Client
}
// NewR2 creates new R2 struct.
func NewR2(
accountID string,
accessKeyID string,
accessKeySecret string,
bucket string,
) (*R2, error) {
r2Resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
return aws.Endpoint{
URL: fmt.Sprintf("https://%s.r2.cloudflarestorage.com", accountID),
}, nil
})
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithEndpointResolverWithOptions(r2Resolver),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, "")),
)
if err != nil {
return nil, fmt.Errorf("creating config: %w", err)
}
client := s3.NewFromConfig(cfg)
return &R2{
Bucket: bucket,
client: client,
}, nil
}
// Upload uploads given body to given key.
func (r2 *R2) Upload(ctx context.Context, key string, body []byte) error {
_, err := r2.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(r2.Bucket),
Key: aws.String(key),
Body: bytes.NewReader(body),
ContentType: aws.String(getContentType(key)),
})
if err != nil {
return fmt.Errorf("uploading object: %w", err)
}
return nil
}