-
Notifications
You must be signed in to change notification settings - Fork 4
/
store.go
93 lines (76 loc) · 1.88 KB
/
store.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
package s3
import (
"bytes"
"io"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"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"
)
// Config is configuration related to storage in S3
type Config struct {
Endpoint string `yaml:"endpoint"`
Bucket string `yaml:"bucket"`
Region string `yaml:"region"`
ID string `yaml:"id"`
Key string `yaml:"key"`
Token string `yaml:"token"`
}
// Store allows you to access your files in an S3 bucket
type Store struct {
sess *session.Session
bucket string
}
// NewStore creates a new Store for you
func NewStore(config Config) (*Store, error) {
s3Config := aws.Config{
Region: aws.String(config.Region),
Credentials: credentials.NewStaticCredentials(
config.ID,
config.Key,
config.Token,
),
S3ForcePathStyle: aws.Bool(true),
}
if config.Endpoint != "" {
s3Config.Endpoint = aws.String(config.Endpoint)
}
sess, err := session.NewSession(&s3Config)
if err != nil {
return nil, err
}
store := &Store{
sess: sess,
bucket: config.Bucket,
}
return store, nil
}
// GetByKey retrieves the data at a certain location in your bucket
func (s *Store) GetByKey(key string) (io.Reader, error) {
results, err := s3.New(s.sess).GetObject(&s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
if err != nil {
return nil, err
}
defer func() {
_ = results.Body.Close()
}()
buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, results.Body); err != nil {
return nil, err
}
return buf, nil
}
// Save puts the data at a location in your bucket
func (s *Store) Save(key string, data io.Reader) error {
uploader := s3manager.NewUploader(s.sess)
_, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: data,
})
return err
}