-
Notifications
You must be signed in to change notification settings - Fork 2
/
s3.go
233 lines (199 loc) · 5.84 KB
/
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package upload
import (
"bytes"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"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/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/chadweimer/gomp/modules/conf"
)
// S3Driver is an implementation of Driver that uses the Amazon S3.
type S3Driver struct {
cfg *conf.Config
}
// NewS3Driver constucts a S3Driver.
func NewS3Driver(cfg *conf.Config) S3Driver {
return S3Driver{cfg: cfg}
}
// Save creates or overrites a file with the provided binary data.
func (u S3Driver) Save(filePath string, data []byte) error {
svc := connectToS3(u.cfg)
bucket := u.cfg.UploadPath
key := filepath.ToSlash(filePath)
contentType := http.DetectContentType(data)
_, err := svc.PutObject(&s3.PutObjectInput{
Body: bytes.NewReader(data),
ContentType: &contentType,
Bucket: &bucket,
Key: &key,
})
return err
}
// Delete deletes the file with the specified key, if it exists.
func (u S3Driver) Delete(key string) error {
svc := connectToS3(u.cfg)
bucket := u.cfg.UploadPath
key = filepath.ToSlash(key)
_, err := svc.DeleteObject(&s3.DeleteObjectInput{
Bucket: &bucket,
Key: &key,
})
return err
}
// DeleteAll deletes all files with the specified key prefix.
func (u S3Driver) DeleteAll(keyPrefix string) error {
svc := connectToS3(u.cfg)
bucket := u.cfg.UploadPath
keyPrefix = filepath.ToSlash(keyPrefix)
listOutput, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{
Bucket: &bucket,
Prefix: &keyPrefix,
})
if err != nil {
return err
}
for _, object := range listOutput.Contents {
_, err := svc.DeleteObject(&s3.DeleteObjectInput{
Bucket: &bucket,
Key: object.Key,
})
if err != nil {
return err
}
}
return nil
}
// List retrieves information about all uploaded files with the specified key prefix.
func (u S3Driver) List(keyPrefix string) ([]FileInfo, error) {
var fileInfos []FileInfo
svc := connectToS3(u.cfg)
bucket := u.cfg.UploadPath
prefix := filepath.ToSlash(filepath.Join(keyPrefix, "images"))
listOutput, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{
Bucket: &bucket,
Prefix: &prefix,
})
if err != nil {
return fileInfos, err
}
for _, object := range listOutput.Contents {
urlSegments := strings.Split(*object.Key, "/")
name := urlSegments[len(urlSegments)-1]
origURL := "/uploads/" + *object.Key
// TODO: Should we do a HEAD or similar request to ensure the thumbnail exists?
thumbKey := strings.Replace(*object.Key, "/images/", "/thumbs/", 1)
thumbURL := "/uploads/" + thumbKey
fileInfo := FileInfo{
Name: name,
URL: origURL,
ThumbnailURL: thumbURL,
}
fileInfos = append(fileInfos, fileInfo)
}
return fileInfos, nil
}
// S3Static is a middleware handler that serves static files from Amazon S3.
// If the file does not exist on the S3, it passes along to the next middleware
// in the chain.
type S3Static struct {
cfg *conf.Config
// Prefix is the optional prefix used to serve the static content
Prefix string
}
// NewS3Static returns a new instance of S3Static
func NewS3Static(cfg *conf.Config) *S3Static {
return &S3Static{
cfg: cfg,
Prefix: "",
}
}
func (s *S3Static) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if r.Method != "GET" && r.Method != "HEAD" {
next(rw, r)
return
}
filePath := r.URL.Path
// if we have a prefix, filter requests by stripping the prefix
if s.Prefix != "" {
if !strings.HasPrefix(filePath, s.Prefix) {
next(rw, r)
return
}
filePath = filePath[len(s.Prefix):]
if filePath != "" && filePath[0] != '/' {
next(rw, r)
return
}
}
svc := connectToS3(s.cfg)
bucket := s.cfg.UploadPath
// Build the GetObject request, passing along conditional GET parameters
getReq := s3.GetObjectInput{
Bucket: &bucket,
Key: &filePath,
}
s.passThroughReqHeaders(&getReq, r.Header)
// Make the request and check the error
getResp, err := svc.GetObject(&getReq)
if err != nil {
s3err, ok := err.(awserr.Error)
// 304 code is expected
if ok && s3err.Code() != "304NotModified" {
// discard the error?
next(rw, r)
return
}
}
var buf []byte
// If we got content, read it, including associated headers
if getResp.ContentLength != nil && *getResp.ContentLength > 0 {
defer getResp.Body.Close()
// Don't read the file back if we're just a HEAD request
if r.Method != "HEAD" {
buf, err = ioutil.ReadAll(getResp.Body)
if err != nil {
// discard the error?
next(rw, r)
return
}
}
}
s.passThroughRespHeaders(getResp, rw.Header())
// Serve up the file to the client
http.ServeContent(rw, r, filePath, *getResp.LastModified, bytes.NewReader(buf))
}
func (s *S3Static) passThroughReqHeaders(getReq *s3.GetObjectInput, reqHeader http.Header) {
if ifModSince, err := time.Parse(http.TimeFormat, reqHeader.Get("If-Modified-Since")); err == nil {
getReq.IfModifiedSince = &ifModSince
}
if ifNoneMatch := reqHeader.Get("If-None-Match"); ifNoneMatch != "" {
getReq.IfNoneMatch = &ifNoneMatch
}
}
func (s *S3Static) passThroughRespHeaders(getResp *s3.GetObjectOutput, respHeader http.Header) {
if getResp.ContentType != nil && *getResp.ContentType != "" {
respHeader.Set("Content-Type", *getResp.ContentType)
}
if getResp.ContentEncoding != nil && *getResp.ContentEncoding != "" {
respHeader.Set("Content-Encoding", *getResp.ContentEncoding)
}
if getResp.ETag != nil && *getResp.ETag != "" {
respHeader.Set("ETag", *getResp.ETag)
}
}
func connectToS3(cfg *conf.Config) *s3.S3 {
awsConfig := new(aws.Config)
if cfg.AwsRegion != "" {
awsConfig.Region = &cfg.AwsRegion
}
if cfg.AwsAccessKeyID != "" && cfg.AwsSecretAccessKey != "" {
awsConfig.Credentials = credentials.NewStaticCredentials(cfg.AwsAccessKeyID, cfg.AwsSecretAccessKey, "")
}
return s3.New(session.New(awsConfig))
}