-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3db.go
90 lines (81 loc) · 2.11 KB
/
s3db.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 s3db
import (
"bytes"
"context"
"errors"
"io"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/onsi/disco/config"
)
var TIMEOUT = time.Second * 10
var ErrObjectNotFound = errors.New("object not found")
var ErrTimeout = errors.New("timed out")
type S3DBInt interface {
FetchObject(key string) ([]byte, error)
PutObject(key string, data []byte) error
}
type S3DB struct {
svc *s3.S3
bucket string
env string
}
func NewS3DB() (*S3DB, error) {
conf := config.LoadConfig()
sess, err := session.NewSession(&aws.Config{
Region: aws.String(conf.AWSRegion),
Credentials: credentials.NewStaticCredentials(conf.AWSAccessKey, conf.AWSSecretKey, ""),
})
if err != nil {
return nil, err
}
return &S3DB{
svc: s3.New(sess),
bucket: conf.AWSS3Bucket,
env: conf.Env,
}, nil
}
func (s3db *S3DB) FetchObject(okey string) ([]byte, error) {
key := s3db.env + "/" + okey
ctx, cancel := context.WithTimeout(context.Background(), TIMEOUT)
defer cancel()
resp, err := s3db.svc.GetObjectWithContext(ctx, &s3.GetObjectInput{
Bucket: aws.String(s3db.bucket),
Key: aws.String(key),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == s3.ErrCodeNoSuchKey {
return nil, ErrObjectNotFound
} else if aerr.Code() == request.CanceledErrorCode {
return nil, ErrTimeout
}
}
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func (s3db *S3DB) PutObject(okey string, data []byte) error {
key := s3db.env + "/" + okey
ctx, cancel := context.WithTimeout(context.Background(), TIMEOUT)
defer cancel()
_, err := s3db.svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
Bucket: aws.String(s3db.bucket),
Key: aws.String(key),
Body: aws.ReadSeekCloser(bytes.NewReader(data)),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == request.CanceledErrorCode {
return ErrTimeout
}
}
}
return err
}