-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (77 loc) · 1.91 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
91
92
93
94
package main
import (
"fmt"
"log"
"os"
"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"
)
func Upload(bucket, filename string) error {
// Open session
sess := session.Must(session.NewSession())
// Open file to upload
file, err := os.Open(filename)
defer file.Close()
if err != nil {
return fmt.Errorf("Unable to open file %q, %v", filename, err)
}
uploader := s3manager.NewUploader(sess)
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(filename),
Body: file,
})
if err != nil {
return fmt.Errorf("Unable to upload %q to %q, %v", filename, bucket, err)
}
return nil
}
func Download(bucket, filename string) error {
// Open session
sess := session.Must(session.NewSession())
// Create new file to fullfill with bucket content
// Will fail if file exists
file, err := os.Create(filename)
defer file.Close()
if err != nil {
return fmt.Errorf("Unable to open file %q, %v", filename, err)
}
downloader := s3manager.NewDownloader(sess)
_, err = downloader.Download(file,
&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(filename),
})
if err != nil {
return fmt.Errorf("Unable to download item %q, %v", filename, err)
}
return nil
}
func main() {
if len(os.Args) != 4 {
log.Fatalf("Usage: %s [upload|download] bucket_name local_filename",
os.Args[0])
os.Exit(1)
}
action := os.Args[1]
bucket := os.Args[2]
filename := os.Args[3]
switch action {
case "upload":
err := Upload(bucket, filename)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket)
case "download":
err := Download(bucket, filename)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
fmt.Printf("Successfully downloaded %q from %q\n", filename, bucket)
}
}