-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws_s3_service.go
96 lines (84 loc) · 1.85 KB
/
aws_s3_service.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package awsx
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"io"
)
type S3 struct {
S3Service
}
type S3Service interface {
Upload(
ctx context.Context,
path string,
body io.Reader,
options ...S3Option,
) (
bool,
error,
)
ObjectEndpoint(options ...S3Option) string
}
type s3Service struct {
s3 *s3Client
opts []S3Option
}
// NewS3Service creates a new s3 service.
// If additional options are given
// this options will be used for the upcoming requests to the aws client.
func NewS3Service(
opts ...S3Option,
) (S3Service, error) {
options := applyS3Options(opts)
s3Client := initS3Session(options)
return &s3Service{
s3: s3Client,
opts: opts,
}, nil
}
func (s *s3Service) Upload(
ctx context.Context,
path string,
body io.Reader,
options ...S3Option,
) (
bool,
error,
) {
reqOptions := s.applyOptions(options)
_, err := s.s3.PutObject(
ctx, &s3.PutObjectInput{
Bucket: aws.String(reqOptions.bucketName),
Key: aws.String(path),
Body: body,
},
)
if err != nil {
fmt.Printf(
"Couldn't upload file %v to %v:%v. error: %v\n",
body, reqOptions.bucketName, path, err,
)
return true, err
}
return true, err
}
// ObjectEndpoint build the endpoint on which the object of the bucket can be accessed.
// This can be used to add some path behind the endpoint of the object itself.
func (s *s3Service) ObjectEndpoint(options ...S3Option) string {
reqOptions := s.applyOptions(options)
return fmt.Sprintf("https://%s.s3.%s.amazonaws.com", reqOptions.bucketName, reqOptions.region)
}
func (s *s3Service) applyOptions(options []S3Option) *S3RequestConfig {
req := &S3RequestConfig{}
// per client options apply first
for _, option := range s.opts {
option(req)
}
// per request options
for _, option := range options {
option(req)
}
return req
}