-
Notifications
You must be signed in to change notification settings - Fork 2
/
s3.go
90 lines (77 loc) · 1.9 KB
/
s3.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
package aws
import (
"bytes"
"io"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
// S3 is AWS S3 client
type S3 struct {
uploader interface {
Upload(*s3manager.UploadInput, ...func(*s3manager.Uploader)) (*s3manager.UploadOutput, error)
}
downloader interface {
Download(io.WriterAt, *s3.GetObjectInput, ...func(*s3manager.Downloader)) (int64, error)
}
bucket string
key string
ready bool
reader *bytes.Buffer
}
// NewS3WithSession creates new AWS S3 client with session sess
func NewS3WithSession(bucket, key string, sess *session.Session) (*S3, error) {
uploader := s3manager.NewUploader(sess)
downloader := s3manager.NewDownloader(sess)
return &S3{
uploader: uploader,
downloader: downloader,
bucket: bucket,
key: key,
ready: false,
}, nil
}
// NewS3 returns new AWS S3 client
func NewS3(bucket, key string) (*S3, error) {
sess, err := session.NewSession()
if err != nil {
return nil, err
}
return NewS3WithSession(bucket, key, sess)
}
// Write writes data to S3 bucket
func (s *S3) Write(data []byte) (int, error) {
body := bytes.NewBuffer(data)
// Upload the file to S3.
_, err := s.uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(s.bucket),
Key: aws.String(s.key),
Body: body,
})
if err != nil {
return 0, err
}
return len(data), nil
}
// Read reads data from S3 bucket
func (s *S3) Read(data []byte) (int, error) {
if !s.ready {
buf := &aws.WriteAtBuffer{}
// Write the contents of S3 Object to the file
_, err := s.downloader.Download(buf, &s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(s.key),
})
if err != nil {
return 0, err
}
s.reader = bytes.NewBuffer(buf.Bytes())
s.ready = true
}
n, err := s.reader.Read(data)
if err != nil {
s.ready = false
}
return n, err
}