-
Notifications
You must be signed in to change notification settings - Fork 3
/
oss.go
117 lines (99 loc) · 2.4 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
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
package google
import (
"cloud.google.com/go/storage"
"context"
"fmt"
"github.com/JerryZhou343/cctool/internal/status"
"github.com/JerryZhou343/cctool/internal/utils"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"io"
"os"
"path/filepath"
"strconv"
"time"
)
type GoogleOSS struct {
bucketName string
credentialsFile string
}
func NewGoogleOSS(bucketName, credentialsFile string) *GoogleOSS {
return &GoogleOSS{
bucketName: bucketName,
credentialsFile: credentialsFile,
}
}
func (g *GoogleOSS) UploadFile(srcFilePath string) (uri string, obj string, err error) {
if !utils.CheckFileExist(srcFilePath) {
err = status.ErrFileNotExits
return
}
fileName := filepath.Base(srcFilePath)
ctx := context.Background()
f, err := os.Open(srcFilePath)
if err != nil {
return
}
defer f.Close()
//分日期存储
date := time.Now()
year := date.Year()
month := date.Month()
day := date.Day()
obj = strconv.Itoa(year) + "/" + strconv.Itoa(int(month)) + "/" + strconv.Itoa(day) + "/" + fileName
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
client, err := storage.NewClient(ctx, option.WithCredentialsFile(g.credentialsFile))
if err != nil {
return
}
wc := client.Bucket(g.bucketName).Object(obj).NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
return
}
if err = wc.Close(); err != nil {
return
}
return g.GetObjectFileUrl(obj), obj, nil
}
func (g *GoogleOSS) GetListBuckets() (ret []string, err error) {
var (
attrs *storage.BucketAttrs
)
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
client, err := storage.NewClient(ctx, option.WithCredentialsFile(g.credentialsFile))
if err != nil {
return
}
it := client.Buckets(ctx, "")
for {
attrs, err = it.Next()
if err == iterator.Done {
break
}
if err != nil {
return
}
ret = append(ret, attrs.Name)
}
return
}
func (g *GoogleOSS) DeleteFile(obj string) (err error) {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
client, err := storage.NewClient(ctx, option.WithCredentialsFile(g.credentialsFile))
if err != nil {
return
}
src := client.Bucket(g.bucketName).Object(obj)
if err := src.Delete(ctx); err != nil {
return err
}
return
}
func (g *GoogleOSS) GetObjectFileUrl(obj string) string {
return fmt.Sprintf("gs://%s/%s", g.bucketName, obj)
}