/
oss.go
82 lines (70 loc) · 1.61 KB
/
oss.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
package storage
import (
"bytes"
"io"
"log"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
type aliOSS struct {
Bucket *oss.Bucket
root string
host string
}
func NewAliOSS(root, host string, opts ...Option) Storage {
o := &options{}
for _, opt := range opts {
opt(o)
}
client, err := oss.New(o.endpoint, o.secretId, o.secretKey)
if err != nil {
log.Panic("oss.New 失败", err)
}
bucket, err := client.Bucket(o.bucketName)
if err != nil {
log.Panic("storage.Bucket 失败", err)
}
return &aliOSS{
Bucket: bucket,
root: root,
host: host,
}
}
func (a *aliOSS) Url(path string) string {
return a.host + a.Path(path)
}
func (a *aliOSS) Path(path string) string {
return strings.TrimLeft(a.root+path, "/")
}
func (a *aliOSS) Exists(path string) (bool, error) {
return a.Bucket.IsObjectExist(a.Path(path))
}
func (a *aliOSS) Get(path string) (io.Reader, error) {
readCloser, err := a.Bucket.GetObject(a.Path(path))
if err != nil {
return nil, err
}
defer readCloser.Close()
buf := bytes.NewBuffer(nil)
if _, err := buf.ReadFrom(readCloser); err != nil {
return nil, err
}
return buf, err
}
func (a *aliOSS) Put(path string, reader io.Reader) error {
return a.Bucket.PutObject(a.Path(path), reader)
}
func (a *aliOSS) Delete(path string) error {
return a.Bucket.DeleteObject(a.Path(path))
}
func (a *aliOSS) Copy(path1, path2 string) error {
_, err := a.Bucket.CopyObject(a.Path(path1), a.Path(path2))
return err
}
func (a *aliOSS) Move(path1, path2 string) error {
err := a.Copy(a.Path(path1), a.Path(path2))
if err != nil {
return err
}
return a.Delete(a.Path(path1))
}