-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgooglebucket.go
114 lines (90 loc) · 2.24 KB
/
googlebucket.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
package cbgooglebucket
import (
"cloud.google.com/go/storage"
"context"
"errors"
"fmt"
"google.golang.org/api/option"
"io"
)
type Storage struct {
client *storage.Client
bucket string
}
type Config struct {
Bucket string
CredentialsJson []byte
}
func New(config Config) (*Storage, error) {
if config.Bucket == "" {
return nil, errors.New("invalid bucket name")
}
if len(config.CredentialsJson) == 0 {
return nil, errors.New("empty credentials json")
}
client, e := storage.NewClient(context.Background(), option.WithCredentialsJSON(config.CredentialsJson))
if e != nil {
return nil, e
}
return &Storage{bucket: config.Bucket, client: client}, nil
}
func (s *Storage) checkFilename(filename string) error {
if filename == "" || filename == "." || filename == ".." {
return fmt.Errorf("invalid filename: %s", filename)
}
return nil
}
func (s *Storage) Upload(filename string, reader io.Reader) error {
if e := s.checkFilename(filename); e != nil {
return e
}
object := s.client.Bucket(s.bucket).Object(filename)
ctx := context.Background()
writer := object.NewWriter(ctx)
_, e := io.Copy(writer, reader)
if e != nil {
return e
}
if e := writer.Close(); e != nil {
return e
}
return nil
}
func (s *Storage) Download(filename string, writer io.Writer) error {
if e := s.checkFilename(filename); e != nil {
return e
}
object := s.client.Bucket(s.bucket).Object(filename)
ctx := context.Background()
reader, e := object.NewReader(ctx)
if e != nil {
return e
}
_, e = io.Copy(writer, reader)
if e != nil {
return e
}
if e := reader.Close(); e != nil {
return e
}
return nil
}
func (s *Storage) Concat(destination string, filenames ...string) error {
if e := s.checkFilename(destination); e != nil {
return e
}
dst := s.client.Bucket(s.bucket).Object(destination)
var objects []*storage.ObjectHandle
for _, filename := range filenames {
objects = append(objects, s.client.Bucket(s.bucket).Object(filename))
}
_, e := dst.ComposerFrom(objects...).Run(context.Background())
return e
}
func (s *Storage) Delete(filename string) error {
if e := s.checkFilename(filename); e != nil {
return e
}
object := s.client.Bucket(s.bucket).Object(filename)
return object.Delete(context.Background())
}