-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathgcs.go
74 lines (61 loc) · 1.67 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
63
64
65
66
67
68
69
70
71
72
73
74
package gcs
import (
"context"
"io"
"mime"
"path/filepath"
"cloud.google.com/go/storage"
"github.com/ulule/gostorages"
"google.golang.org/api/option"
)
// Storage is a gcs storage.
type Storage struct {
bucket *storage.BucketHandle
}
// NewStorage returns a new Storage.
func NewStorage(ctx context.Context, credentialsFile, bucket string) (*Storage, error) {
client, err := storage.NewClient(ctx, option.WithCredentialsFile(credentialsFile))
if err != nil {
return nil, err
}
return &Storage{bucket: client.Bucket(bucket)}, nil
}
// Save saves content to path.
func (g *Storage) Save(ctx context.Context, content io.Reader, path string) (rerr error) {
w := g.bucket.Object(path).NewWriter(ctx)
w.ContentType = mime.TypeByExtension(filepath.Ext(path))
defer func() {
if err := w.Close(); err != nil {
rerr = err
}
}()
if _, err := io.Copy(w, content); err != nil {
return err
}
return rerr
}
// Stat returns path metadata.
func (g *Storage) Stat(ctx context.Context, path string) (*gostorages.Stat, error) {
attrs, err := g.bucket.Object(path).Attrs(ctx)
if err == storage.ErrObjectNotExist {
return nil, gostorages.ErrNotExist
} else if err != nil {
return nil, err
}
return &gostorages.Stat{
ModifiedTime: attrs.Updated,
Size: attrs.Size,
}, nil
}
// Open opens path for reading.
func (g *Storage) Open(ctx context.Context, path string) (io.ReadCloser, error) {
r, err := g.bucket.Object(path).NewReader(ctx)
if err == storage.ErrObjectNotExist {
return nil, gostorages.ErrNotExist
}
return r, err
}
// Delete deletes path.
func (g *Storage) Delete(ctx context.Context, path string) error {
return g.bucket.Object(path).Delete(ctx)
}