-
Notifications
You must be signed in to change notification settings - Fork 3
/
uploader.go
51 lines (43 loc) · 1006 Bytes
/
uploader.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
package s3
import (
"bytes"
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/unanet/go/pkg/errors"
)
type Config struct {
Bucket string
}
type Location struct {
Bucket string `json:"bucket"`
Key string `json:"key"`
Url string `json:"url"`
}
type Uploader struct {
Bucket string
s3 *s3manager.Uploader
}
func NewUploader(sess *session.Session, config Config) *Uploader {
return &Uploader{
s3: s3manager.NewUploader(sess),
Bucket: config.Bucket,
}
}
func (u Uploader) Upload(ctx context.Context, key string, body []byte) (*Location, error) {
bodyReader := bytes.NewReader(body)
result, err := u.s3.UploadWithContext(ctx, &s3manager.UploadInput{
Body: bodyReader,
Bucket: aws.String(u.Bucket),
Key: aws.String(key),
})
if err != nil {
return nil, errors.Wrap(err)
}
return &Location{
Bucket: u.Bucket,
Key: key,
Url: result.Location,
}, nil
}