-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3.go
160 lines (142 loc) · 3.53 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Package S3 provides the ability to upload file to Aamzon S3
package s3
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"mime"
"net/http"
"path"
"sort"
"strings"
"time"
)
func IsValidBucket(bucket string) bool {
l := len(bucket)
if l < 3 || l > 63 {
return false
}
valid := false
prev := byte('.')
for i := 0; i < len(bucket); i++ {
c := bucket[i]
switch {
default:
return false
case 'a' <= c && c <= 'z':
valid = true
case '0' <= c && c <= '9':
// Is allowed, but bucketname can't be just numbers.
// Therefore, don't set valid to true
case c == '-':
if prev == '.' {
return false
}
case c == '.':
if prev == '.' || prev == '-' {
return false
}
}
prev = c
}
if prev == '-' || prev == '.' {
return false
}
return valid
}
// Init method take Amazon credential. Acesskey and SecretKey
func Init(accesskey string, secretKey string) *Client {
return &Client{&Auth{accesskey, secretKey, "s3-eu-west-1.amazonaws.com"}}
}
type Client struct {
*Auth
}
type Item struct {
Key string
Size int64
Index int
ImageUrl string
}
type ListBucketResults struct {
Contents []Item
}
type SortedItems []Item
func (s SortedItems) Len() int {
return len(s)
}
func (s SortedItems) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type ByKey struct{ SortedItems }
func (s ByKey) Less(i, j int) bool {
return s.SortedItems[i].Key > s.SortedItems[j].Key
}
// Bucket url
func (c *Client) bucketURL(bucket string) string {
if IsValidBucket(bucket) && !strings.Contains(bucket, ".") {
return fmt.Sprintf("https://%s.%s/", bucket, c.hostname())
}
return fmt.Sprintf("https://%s/%s/", c.hostname(), bucket)
}
// Full url with file key
func (c *Client) keyURL(bucket, key string) string {
return c.bucketURL(bucket) + key
}
func (c *Client) ListBucket(bucket string) (result *ListBucketResults, err error) {
bucketUrl := c.bucketURL(bucket)
url := fmt.Sprintf("%s?max-keys=800", bucketUrl)
req, _ := http.NewRequest("GET", url, nil)
c.Auth.SignRequest(req)
httpClient := &http.Client{}
bucketRes, requestErr := httpClient.Do(req)
if requestErr != nil {
return nil, requestErr
}
defer bucketRes.Body.Close()
var bucketResult ListBucketResults
if err := xml.NewDecoder(bucketRes.Body).Decode(&bucketResult); err != nil {
return nil, err
}
sort.Sort(ByKey{bucketResult.Contents})
for k, _ := range bucketResult.Contents {
bucketResult.Contents[k].ImageUrl = fmt.Sprintf("%s%s", bucketUrl, bucketResult.Contents[k].Key)
}
return &bucketResult, nil
}
// Upload file to given bucket
// File key
// Bucket name
// data file
// Return full file url if succeeded
func (c *Client) Upload(key, bucket string, data []byte) (fileUrl string, err error) {
if data == nil {
var errorEmptyData = errors.New("data cannot be null")
return "", errorEmptyData
}
url := c.keyURL(bucket, key)
req, _ := http.NewRequest("PUT", url, nil)
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
ext := path.Ext(key)
mimeType := mime.TypeByExtension(ext)
req.Header.Set("Content-Type", mimeType)
req.Header.Set("Cache-Control", "max-age=94608000")
req.Header.Set("x-amz-meta-Cache-Control", "max-age=94608000")
req.ContentLength = int64(len(data))
body := bytes.NewBuffer(data)
req.Body = ioutil.NopCloser(body)
c.Auth.SignRequest(req)
httpClient := &http.Client{}
res, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
_, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return "", readErr
}
full := fmt.Sprintf("%s", url)
return full, nil
}