forked from alephao/bitrise-step-s3-cache-push
-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws.go
67 lines (56 loc) · 1.46 KB
/
aws.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
package main
import (
"fmt"
"log"
"os"
"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"
)
type AwsS3 struct {
sess *session.Session
bucketName string
}
func NewAwsS3(awsRegion, accessKey, secretKey, bucket string) *AwsS3 {
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
aws.NewConfig()
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(awsRegion),
Credentials: creds,
}))
return &AwsS3{
sess: sess,
bucketName: bucket,
}
}
func (a *AwsS3) CacheExists(key string) bool {
svc := s3.New(a.sess)
obj, err := svc.ListObjects(&s3.ListObjectsInput{
Bucket: aws.String(a.bucketName),
MaxKeys: aws.Int64(1),
Prefix: aws.String(key),
})
if err != nil {
log.Printf("An error occurred when hitting the cache: %s. Assuming there is no cache\n", err.Error())
return false
}
return len(obj.Contents) > 0
}
func (a *AwsS3) UploadToAws(key, pathToFile string) error {
uploader := s3manager.NewUploader(a.sess)
f, err := os.Open(pathToFile)
if err != nil {
return fmt.Errorf("failed to open file %q, %v", pathToFile, err)
}
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(a.bucketName),
Key: aws.String(key),
Body: f,
})
if err != nil {
return fmt.Errorf("failed to upload file, %v", err)
}
return nil
}