oss.go
1.7 KB
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
package utils
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/google/uuid"
"io"
"path"
"time"
)
type RouterConfig struct {
OssEndPoint string
AccessKeyID string
AccessKeySecret string
BuckName string
AppProject string
RegionID string
RoleArn string
}
type (
CreateStsAuthRequest struct {
Files []string `json:"files"`
}
CreateStsAuthResponse struct {
Certificate interface{} `json:"certificate"`
Files []BuckObject `json:"files"`
}
Object struct {
Key string
Value io.Reader
}
BuckObject struct {
DefaultHost string `json:"host"`
Key string `json:"key"`
Path string `json:"path"`
FileName string `json:"fileName"`
}
)
func NewBucket(config RouterConfig) (*oss.Bucket, error) {
client, err := oss.New(config.OssEndPoint, config.AccessKeyID, config.AccessKeySecret)
if err != nil {
return nil, err
}
bucket, err := client.Bucket(config.BuckName)
if err != nil {
return nil, err
}
return bucket, nil
}
func CreateObjects(bucket *oss.Bucket, objects ...Object) error {
for _, object := range objects {
err := bucket.PutObject(object.Key, object.Value)
if err != nil {
return err
}
}
return nil
}
func DeleteObjects(bucket *oss.Bucket, objects ...string) error {
for _, object := range objects {
err := bucket.DeleteObject(object)
if err != nil {
return err
}
}
return nil
}
func GetFileName(projectName, filename string) string {
date := time.Now().Format("20060102")
ext := path.Ext(filename)
if len(projectName) == 0 {
projectName = "default"
}
uid, _ := uuid.NewUUID()
filename = fmt.Sprintf("%v%v", uid.String(), ext)
sourcePath := fmt.Sprintf("%v/%v/%v", projectName, date, filename)
return sourcePath
}