-
Notifications
You must be signed in to change notification settings - Fork 16
/
gcpstore.go
84 lines (68 loc) · 2.06 KB
/
gcpstore.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
package contentstore
import (
"context"
"io"
"cloud.google.com/go/storage"
"github.com/ashirt-ops/ashirt-server/backend"
"github.com/google/uuid"
)
type GCPStore struct {
bucketName string
gcpClient *storage.Client
bucketAccess *storage.BucketHandle
creationContext context.Context
}
// NewGCPStore provides a mechanism to initialize a GCP client
func NewGCPStore(bucketName string) (*GCPStore, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return nil, backend.WrapError("Unable to establish an gcp session", err)
}
return &GCPStore{
bucketName: bucketName,
gcpClient: client,
bucketAccess: client.Bucket(bucketName),
creationContext: ctx,
}, nil
}
// Upload stores a file in the Google Cloud bucket configured when the gcpStore was created
func (s *GCPStore) Upload(data io.Reader) (string, error) {
key := uuid.New().String()
err := s.UploadWithName(key, data)
return key, err
}
// UploadWithName is a test/dev helper that places a file on Google Cloud with a given name
// This is not intended for general use.
func (s *GCPStore) UploadWithName(key string, data io.Reader) error {
ctx := context.Background()
wc := s.bucketAccess.Object(key).NewWriter(ctx)
if _, err := io.Copy(wc, data); err != nil {
return backend.WrapError("Upload to gcp failed", err)
}
if err := wc.Close(); err != nil {
return backend.WrapError("Unable to close gcp writer", err)
}
return nil
}
// Read retrieves the indicated file from Google Cloud
func (s *GCPStore) Read(key string) (io.Reader, error) {
ctx := context.Background()
res, err := s.bucketAccess.Object(key).NewReader(ctx)
if err != nil {
return nil, backend.WrapError("Unable to read from gcp", err)
}
return res, nil
}
// Delete removes the indicated file from GCP
func (s *GCPStore) Delete(key string) error {
ctx := context.Background()
err := s.bucketAccess.Object(key).Delete(ctx)
if err != nil {
return backend.WrapError("Delete from gcp failed", err)
}
return nil
}
func (s *GCPStore) Name() string {
return "gcp"
}