-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage_s3.go
117 lines (92 loc) · 2.59 KB
/
storage_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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package imageresizer
import (
"fmt"
"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"
"io"
"os"
"path/filepath"
"time"
)
type s3client struct {
s3 *s3.S3
bucket string
}
func NewS3Client(endpoint string, bucket string, key string, secret string, region string) *s3client {
s, err := session.NewSession(&aws.Config{
Endpoint: aws.String(endpoint),
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials(key, secret, ""),
})
if err != nil {
fmt.Printf("Unable create New S3 s %v\n", err)
os.Exit(1)
}
return &s3client{s3.New(s), bucket}
}
func (c *s3client) DownloadFile(path string, outputPath string) (f *os.File, err error) {
f, _, err = c.DownloadFileWithModTime(path, outputPath)
return
}
func (c *s3client) DownloadFileWithModTime(path string, outputPath string) (f *os.File, t *time.Time, err error) {
resp, err := c.getContent(path)
if err != nil {
return nil, nil, err
}
t = resp.LastModified
defer resp.Body.Close()
if outputPath == "" {
f, err = CreateTempFileFromReader(resp.Body, filepath.Ext(path))
} else {
_, err = WriteFileFromReader(outputPath, resp.Body)
if err != nil {
return
}
f, err = os.Open(outputPath)
}
return
}
func (c *s3client) UploadContentReaderIfNewer(path string, time time.Time, content io.ReadSeeker) (bool, error) {
resp, err := c.headContent(path)
if err == nil && resp.LastModified.After(time) {
return false, nil
}
err = c.UploadContentReader(path, content)
if err != nil {
return false, err
}
return true, nil
}
func (c *s3client) UploadContentReader(path string, content io.ReadSeeker) error {
mime, err := GetReaderContentType(content)
if err != nil {
return err
}
return c.putContent(path, content, mime)
}
func (c *s3client) putContent(path string, content io.ReadSeeker, mime string) (err error) {
_, err = c.s3.PutObject(&s3.PutObjectInput{
Key: aws.String(path),
Body: content,
Bucket: aws.String(c.bucket),
ContentType: aws.String(mime),
ContentDisposition: aws.String("attachment"),
})
return
}
func (c *s3client) getContent(path string) (resp *s3.GetObjectOutput, err error) {
resp, err = c.s3.GetObject(&s3.GetObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(path),
})
return
}
func (c *s3client) headContent(path string) (resp *s3.HeadObjectOutput, err error) {
resp, err = c.s3.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(path),
})
return
}