/
s3.go
101 lines (79 loc) · 2.35 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
package aws
import (
"github.com/apibrew/apibrew/pkg/util"
"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"
"github.com/dop251/goja"
"time"
)
type s3Object struct {
session *session.Session
bucketName string
}
func (s *s3Object) PreSignDownload(fileName string) string {
uploader := s3manager.NewDownloader(s.session)
var expireDuration = time.Hour * 24 * 7
s3Req, _ := uploader.S3.GetObjectRequest(&s3.GetObjectInput{
Bucket: util.Pointer(s.bucketName),
Key: util.Pointer(fileName),
})
url, _, err := s3Req.PresignRequest(expireDuration)
if err != nil {
panic(err)
}
return url
}
func (s *s3Object) PreSignUpload(fileName string) string {
uploader := s3manager.NewUploader(s.session)
var expireDuration = time.Hour * 24 * 7
s3Req, _ := uploader.S3.PutObjectRequest(&s3.PutObjectInput{
Bucket: util.Pointer(s.bucketName),
Key: util.Pointer(fileName),
})
url, _, err := s3Req.PresignRequest(expireDuration)
if err != nil {
panic(err)
}
return url
}
func (s *s3Object) Delete(fileName string) {
uploader := s3manager.NewUploader(s.session)
_, err := uploader.S3.DeleteObject(&s3.DeleteObjectInput{
Bucket: util.Pointer(s.bucketName),
Key: util.Pointer(fileName),
})
if err != nil {
panic(err)
}
}
type Config struct {
Region string
Endpoint string
Credentials struct {
AccessKeyID string
SecretAccessKey string
}
S3ForcePathStyle bool
}
func prepareAwsConfig(config Config) *aws.Config {
awsConfig := &aws.Config{}
awsConfig.Region = util.Pointer(config.Region)
awsConfig.Endpoint = util.Pointer(config.Endpoint)
awsConfig.Credentials = credentials.NewStaticCredentials(config.Credentials.AccessKeyID, config.Credentials.SecretAccessKey, "")
awsConfig.S3ForcePathStyle = util.Pointer(config.S3ForcePathStyle)
return awsConfig
}
func Register(vm *goja.Runtime) error {
return vm.Set("s3", func(config Config, bucketName string) map[string]interface{} {
sess := session.Must(session.NewSession(prepareAwsConfig(config)))
obj := &s3Object{session: sess, bucketName: bucketName}
return map[string]interface{}{
"preSignDownload": obj.PreSignDownload,
"preSignUpload": obj.PreSignUpload,
"delete": obj.Delete,
}
})
}