-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
67 lines (56 loc) · 1.51 KB
/
client.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
package storage
import (
"cloud.google.com/go/storage"
"context"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"strings"
)
type Client struct {
s *storage.Client
}
// Open serves directly a file. In the future, we will support generating signed links and redirecting,
// so we don't have to stream the file (at a performance and data streaming cost). The format for the name of the file is
// bucket/path/to/file.ext
func (c *Client) Open(name string) (http.File, error) {
bucket, key, err := parsePath(name)
if err != nil {
return nil, err
}
object := c.s.Bucket(bucket).Object(key)
o, err := object.NewReader(context.Background())
if err != nil {
return nil, err
}
return &gcsFile{
obj: object,
Reader: o,
}, nil
}
// Save saves a file to storage. Argument name must be of the syntax bucket/path/to/file.ext
func (c *Client) Save(name string, file io.ReadCloser) (string, int64, error) {
bucket, key, err := parsePath(name)
if err != nil {
return "", 0, err
}
object := c.s.Bucket(bucket).Object(key)
w := object.NewWriter(context.Background())
defer func() {
if err = w.Close(); err != nil {
log.WithField("Error", err).Error("Error closing writer")
}
}()
written, err := io.Copy(w, file)
if err != nil {
return "", written, err
}
return strings.Join([]string{bucket, key}, "/"), written, nil
}
func (c *Client) Delete(name string) error {
bucket, key, err := parsePath(name)
if err != nil {
return err
}
return c.s.Bucket(bucket).Object(key).Delete(context.Background())
}