/
gcp.go
80 lines (66 loc) · 1.55 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
package datastorage
import (
"bytes"
"context"
"io"
"io/ioutil"
"time"
"cloud.google.com/go/storage"
)
// GCPStorage represents a Google Cloud Storage object.
type GCPStorage struct {
bucket string
object string
}
// NewGCPStorage returns a Google Cloud storage item given a bucket and an object
// path.
func NewGCPStorage(bucket string, object string) *GCPStorage {
return &GCPStorage{
bucket: bucket,
object: object,
}
}
// Load downloads an object from a bucket and returns an error if it cannot
// be read.
func (s *GCPStorage) Load() ([]byte, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return nil, err
}
defer client.Close()
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
rc, err := client.Bucket(s.bucket).Object(s.object).NewReader(ctx)
if err != nil {
return nil, err
}
defer rc.Close()
data, err := ioutil.ReadAll(rc)
if err != nil {
return nil, err
}
return data, nil
}
// Save uploads an object to a bucket and returns an error if it cannot be
// written.
func (s *GCPStorage) Save(b []byte) error {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return err
}
defer client.Close()
f := bytes.NewReader(b)
ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
// Upload an object with storage.Writer.
wc := client.Bucket(s.bucket).Object(s.object).NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
return err
}
if err := wc.Close(); err != nil {
return err
}
return nil
}