-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.go
86 lines (69 loc) · 1.46 KB
/
upload.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
package main
import (
"fmt"
"log"
"mime"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/mitchellh/goamz/aws"
"github.com/mitchellh/goamz/s3"
)
var MaxAttempts = 5
type Upload struct {
Path string
Dir string
Bucket string
PrefixKey string
WaitGroup *sync.WaitGroup
}
func (u *Upload) RelativePath() string {
relativePath := strings.TrimPrefix(u.Path, u.Dir+"/")
if u.PrefixKey != "" {
relativePath = u.PrefixKey + "/" + relativePath
}
return relativePath
}
func (u *Upload) FileType() string {
ext := filepath.Ext(u.Path)
fileType := mime.TypeByExtension(ext)
return fileType
}
func (u *Upload) Put() {
auth, _ := aws.EnvAuth()
client := s3.New(auth, aws.USEast)
b := client.Bucket(u.Bucket)
file, err := os.Open(u.Path)
defer file.Close()
if err != nil {
log.Fatal(err)
}
stat, err := file.Stat()
if err != nil {
log.Fatal(err)
}
headers := map[string][]string{
"Content-Length": {strconv.FormatInt(stat.Size(), 10)},
"Content-Type": {u.FileType()},
"Cache-Control": {"max-age=31104000"},
}
relativePath := u.RelativePath()
attempt := 1
for {
fmt.Printf("[%d] Path: %s\n", attempt, relativePath)
err = b.PutReaderHeader(relativePath, file, stat.Size(), headers, s3.ACL("public-read"))
if err == nil || attempt >= MaxAttempts {
break
}
log.Print(err)
time.Sleep(time.Duration(attempt) * time.Second)
attempt += 1
file.Seek(0 ,0)
}
if err != nil {
log.Fatal(err)
}
}