generated from hapoon/lambda-go-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (77 loc) · 1.73 KB
/
main.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
package main
import (
"context"
"crypto/md5"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"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"
)
var (
region string
downloadBucket string
uploadBucket string
)
func main() {
lambda.Start(HandleRequest)
}
type LambdaEvent struct {
Dl string `json:"download"`
}
func init() {
region = os.Getenv("REGION")
if len(region) == 0 {
log.Fatal("region is empty")
}
downloadBucket = os.Getenv("DOWNLOAD_BUCKET")
if len(downloadBucket) == 0 {
log.Fatal("DOWNLOAD_BUCKET is empty")
}
uploadBucket = os.Getenv("UPLOAD_BUCKET")
if len(uploadBucket) == 0 {
log.Fatal("UPLOAD_BUCKET is empty")
}
}
func HandleRequest(ctx context.Context, event LambdaEvent) (result string, err error) {
if len(event.Dl) == 0 {
err = fmt.Errorf("download is empty")
return
}
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(region),
}))
now := time.Now().String()
hash := md5.Sum([]byte(now))
tmpPath := fmt.Sprintf("/tmp/%x", hash)
tmp, err := os.Create(tmpPath)
if err != nil {
return
}
defer tmp.Close()
downloader := s3manager.NewDownloader(sess)
size, err := downloader.Download(tmp, &s3.GetObjectInput{
Bucket: aws.String(downloadBucket),
Key: aws.String(event.Dl),
})
if err != nil {
return
}
log.Printf("downloaded size: %d", size)
uploader := s3manager.NewUploader(sess)
out, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(uploadBucket),
Key: aws.String(event.Dl),
Body: tmp,
})
if err != nil {
return
}
log.Printf("Uploaded out: %+v", out)
result = "Succeeded"
return
}