-
Notifications
You must be signed in to change notification settings - Fork 3
/
s3.go
89 lines (74 loc) · 1.72 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
package main
import (
"net/http"
"net/url"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"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/sirupsen/logrus"
)
type s3Director struct {
s3Svc *s3.S3
bucket string
prefix string
}
func effectiveKey(prefix, userPath string) string {
userPath = strings.Trim(userPath, "/")
if prefix == "" {
return userPath
}
if userPath == "" {
return prefix
}
return prefix + "/" + userPath
}
func (s *s3Director) Direct(r *http.Request) {
logrus.WithFields(logrus.Fields{
"method": r.Method,
"path": r.URL.Path,
}).Info("request received")
key := effectiveKey(s.prefix, r.URL.Path)
var s3Req *request.Request
switch r.Method {
case http.MethodGet:
s3Req, _ = s.s3Svc.GetObjectRequest(&s3.GetObjectInput{
Bucket: &s.bucket,
Key: aws.String(key),
})
case http.MethodHead:
s3Req, _ = s.s3Svc.HeadObjectRequest(&s3.HeadObjectInput{
Bucket: &s.bucket,
Key: aws.String(key),
})
case http.MethodPut:
s3Req, _ = s.s3Svc.PutObjectRequest(&s3.PutObjectInput{
Bucket: &s.bucket,
Key: aws.String(key),
})
case http.MethodDelete:
s3Req, _ = s.s3Svc.DeleteObjectRequest(&s3.DeleteObjectInput{
Bucket: &s.bucket,
Key: aws.String(key),
})
}
purl, err := s3Req.Presign(10 * time.Minute)
if err != nil {
logrus.WithError(err).Warn("error presigning url")
return
}
r.URL, _ = url.Parse(purl)
r.Host = ""
}
func newS3Director(session *session.Session, url *url.URL) (director, error) {
s3Svc := s3.New(session)
bucket := url.Host
prefix := strings.Trim(url.Path, "/")
return &s3Director{
s3Svc: s3Svc,
bucket: bucket,
prefix: prefix,
}, nil
}