This repository has been archived by the owner on Nov 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cacher.go
66 lines (59 loc) · 1.5 KB
/
cacher.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
package gcs
import (
"bytes"
"context"
"fmt"
"io"
"github.com/joshcarp/gop/pkg/gop"
"cloud.google.com/go/storage"
)
type uploader func(bucket string, object string, r io.Reader) error
func (a GOP) Cache(resource string, content []byte) (err error) {
if content == nil{
return DeleteObjects(a.bucket, resource)
}
if err := a.upload(a.bucket, resource, bytes.NewReader(content)); err != nil {
return fmt.Errorf("%s: %w", gop.CacheWriteError, err)
}
return nil
}
func UploadFile(bucket string, object string, r io.Reader) error {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return fmt.Errorf("storage.NewClient: %v", err)
}
defer client.Close()
// Open local file.
wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
if _, err = io.Copy(wc, r); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
if err := wc.Close(); err != nil {
return fmt.Errorf("Writer.Close: %v", err)
}
return nil
}
func DeleteObjects(bucket, path string)error{
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return fmt.Errorf("storage.NewClient: %v", err)
}
defer client.Close()
objIter := client.Bucket(bucket).Objects(ctx, &storage.Query{Prefix: path})
if objIter == nil {
return fmt.Errorf("nothing found")
}
var a *storage.ObjectAttrs
for err == nil {
a, err = objIter.Next()
if a == nil{
return nil
}
if err := client.Bucket(bucket).Object(a.Name).Delete(ctx); err != nil{
return err
}
}
return err
}