-
Notifications
You must be signed in to change notification settings - Fork 1
/
s3.go
84 lines (69 loc) · 1.67 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
package s3
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/crowdmob/goamz/aws"
"github.com/crowdmob/goamz/s3"
)
func Md5HexDigest(body io.Reader) string {
hash := md5.New()
c, _ := ioutil.ReadAll(body)
io.WriteString(hash, string(c))
return hex.EncodeToString(hash.Sum(nil))
}
type BaseClient struct {
Auth aws.Auth
Bucket string
}
type NamedClient struct {
*BaseClient
}
func NewNamedClient() *NamedClient {
auth, _ := aws.EnvAuth()
return &NamedClient{
&BaseClient{Auth: auth},
}
}
func (nc *NamedClient) SetAuth(key, secret string) *NamedClient {
nc.Auth = aws.Auth{
AccessKey: key,
SecretKey: secret,
}
return nc
}
func (nc *NamedClient) SetBucket(name string) *NamedClient {
nc.Bucket = name
return nc
}
func (nc *NamedClient) PutByString(src, ctype string) (string, error) {
return nc.put(strings.NewReader(src), ctype)
}
func (nc *NamedClient) PutByBytes(src []byte, ctype string) (string, error) {
return nc.put(bytes.NewReader(src), ctype)
}
func (nc *NamedClient) PutByUrl(src string) (dst string, err error) {
resp, err := http.Get(src)
if err != nil {
return
}
defer resp.Body.Close()
return nc.put(resp.Body, resp.Header.Get("Content-Type"))
}
func (nc *NamedClient) put(body io.Reader, ctype string) (dst string, err error) {
b1 := new(bytes.Buffer)
b2 := new(bytes.Buffer)
b3 := new(bytes.Buffer)
io.Copy(io.MultiWriter(b1, b2, b3), body)
bucket := s3.New(nc.Auth, aws.APNortheast).Bucket(nc.Bucket)
clength, _ := ioutil.ReadAll(b1)
dst = fmt.Sprintf("%s.ico", Md5HexDigest(b2))
err = bucket.PutReader(
dst, b3, int64(len(clength)), ctype, s3.PublicRead, s3.Options{})
return
}