-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcp.go
117 lines (104 loc) · 2.51 KB
/
gcp.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 cloudcourier
import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
"cloud.google.com/go/storage"
"google.golang.org/api/iterator"
)
type GcpCloud struct {
Bucket string
}
func (g *GcpCloud) GetProvider() cloudCourierProvider {
return GCP
}
func init() {
storeFunc[GCP] = newGcpClient
}
type GcsClient struct {
// The client we will use in communicating with the gcs
Client *storage.Client
// The name of the bucket to operate on
BucketName string
ctx context.Context
}
func newGcpClient(ccb Provider) (StorageClient, error) {
gcConfig, ok := ccb.(*GcpCloud)
// if ccb.type
if !ok {
return nil, fmt.Errorf("incorrect configuration")
}
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return nil, fmt.Errorf("%s", err)
}
return &GcsClient{
Client: client,
BucketName: gcConfig.Bucket,
ctx: ctx,
}, nil
}
func (g *GcsClient) UploadFile(filePath string, reader io.Reader) error {
var BaseFileName string
if filePath != "" {
BaseFileName = filepath.Base(filePath)
} else {
return errors.New("you did not specify the filepath")
}
obj := g.Client.Bucket(g.BucketName).Object(BaseFileName)
w := obj.NewWriter(g.ctx)
if _, err := io.Copy(w, reader); err != nil {
return fmt.Errorf("you did not set the reader to the file")
}
defer func() error {
if err := w.Close(); err != nil {
return fmt.Errorf("could not upload file")
}
return nil
}()
v, err := obj.Attrs(g.ctx)
if err != nil {
return fmt.Errorf("%s", err)
}
fmt.Println(v)
return nil
}
func (g *GcsClient) ListFiles(directory string) ([]string, error) {
// For lisiting files in a google cloud storage you have to list the name of the bucket
var files []string
it := g.Client.Bucket(directory).Objects(g.ctx, nil)
for {
file, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, errors.New("")
}
files = append(files, file.Name)
}
return files, nil
}
func (g *GcsClient) GetFile(fileID string) (io.Reader, error) {
obj := g.Client.Bucket(g.BucketName).Object(fileID)
r, err := obj.NewReader(g.ctx)
if err != nil {
switch {
case errors.Is(err, storage.ErrObjectNotExist):
return nil, fmt.Errorf(storage.ErrObjectNotExist.Error())
default:
return nil, fmt.Errorf("could not get file")
}
}
return r, nil
}
func (g *GcsClient) DeleteFile(fieldID string) error {
obj := g.Client.Bucket(g.BucketName).Object(fieldID)
if err := obj.Delete(g.ctx); err != nil {
return fmt.Errorf("could not delete file")
}
return nil
}