-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcs.go
62 lines (50 loc) · 1.36 KB
/
gcs.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
package gcs
import (
"context"
"io"
"google.golang.org/api/option"
"github.com/hyperboloide/pipe/rw"
"cloud.google.com/go/storage"
)
// GCS defines a Google Cloud Storage connection to a bucket.
type GCS struct {
rw.Prefixed
Bucket string `json:"bucket"`
ServiceAccountKey string `json:"key"`
bucket *storage.BucketHandle
}
// Start the GCS.
func (rw *GCS) Start() error {
ctx := context.Background()
var client *storage.Client
var err error
if len(rw.ServiceAccountKey) > 0 {
opt := option.WithServiceAccountFile(rw.ServiceAccountKey)
client, err = storage.NewClient(ctx, opt)
} else {
client, err = storage.NewClient(ctx)
}
if err != nil {
return err
}
rw.bucket = client.Bucket(rw.Bucket)
return nil
}
// NewWriter returns a Google Cloud Storage Writer
func (rw *GCS) NewWriter(id string) (io.WriteCloser, error) {
ctx := context.Background()
obj := rw.bucket.Object(rw.Prefixed.Name(id))
return obj.NewWriter(ctx), nil
}
// NewReader returns a Google Cloud Storage Reader
func (rw *GCS) NewReader(id string) (io.ReadCloser, error) {
ctx := context.Background()
obj := rw.bucket.Object(rw.Prefixed.Name(id))
return obj.NewReader(ctx)
}
// Delete an Google Cloud Storage object
func (rw *GCS) Delete(id string) error {
ctx := context.Background()
obj := rw.bucket.Object(rw.Prefixed.Name(id))
return obj.Delete(ctx)
}