-
Notifications
You must be signed in to change notification settings - Fork 3
/
aws.go
89 lines (75 loc) · 1.9 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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, string) {
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, ""
}
if len(obj.Contents) > 0 {
return true, *obj.Contents[0].Key
} else {
return false, ""
}
}
func (a *AwsS3) Download(key, outputPath string) (int64, error) {
downloader := s3manager.NewDownloader(a.sess)
downloadedFile, err := os.Create(outputPath)
if err != nil {
return 0, err
}
defer downloadedFile.Close()
return downloader.Download(
downloadedFile,
&s3.GetObjectInput{
Bucket: aws.String(a.bucketName),
Key: aws.String(key),
},
)
}
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
}