-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgcscache.go
112 lines (90 loc) · 2.22 KB
/
gcscache.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package gcscache
import (
"crypto/md5"
"encoding/hex"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"cloud.google.com/go/storage"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
type Cache struct {
pathPrefix string
bucket *storage.BucketHandle
}
func (c *Cache) Get(key string) (resp []byte, ok bool) {
obj := c.bucket.Object(c.url(key))
rdr, err := obj.NewReader(context.Background())
if err != nil {
return []byte{}, false
}
defer rdr.Close()
resp, err = ioutil.ReadAll(rdr)
if err != nil {
log.Printf("gcscache.Get failed: %s", err)
}
return resp, err == nil
}
func (c *Cache) Set(key string, resp []byte) {
obj := c.bucket.Object(c.url(key))
contentType := http.DetectContentType(resp)
w := obj.NewWriter(context.Background())
w.ContentType = contentType
w.ObjectAttrs.ContentType = contentType
_, err := w.Write(resp)
if err != nil {
log.Printf("gcscache.Set failed: %s", err)
}
err = w.Close()
if err != nil {
log.Printf("gcscache.Set failed: %s", err)
}
}
func (c *Cache) Delete(key string) {
obj := c.bucket.Object(c.url(key))
err := obj.Delete(context.Background())
if err != nil {
log.Printf("gcscache.Delete failed: %s", err)
}
}
func (c *Cache) url(key string) string {
key = cacheKeyToObjectKey(key)
if strings.HasSuffix(c.pathPrefix, "/") {
return c.pathPrefix + key
}
return c.pathPrefix + "/" + key
}
func cacheKeyToObjectKey(key string) string {
h := md5.New()
io.WriteString(h, key)
return hex.EncodeToString(h.Sum(nil))
}
func New(bucketURL string) *Cache {
cfg, err := google.JWTConfigFromJSON([]byte(os.Getenv("GCP_PRIVATE_KEY")), storage.ScopeReadWrite)
if err != nil {
panic(err)
}
ts := cfg.TokenSource(context.Background())
opt := option.WithTokenSource(ts)
client, err := storage.NewClient(context.Background(), opt)
if err != nil {
panic(err)
}
r := regexp.MustCompile("gcs://([^/]+)(/(.+)?)?$")
if !r.MatchString(bucketURL) {
panic("Invalid bucket string format. Must match: gcs://bucket-name/path/prefix")
}
match := r.FindStringSubmatch(bucketURL)
bucketName := match[1]
pathPrefix := match[3]
return &Cache{
pathPrefix: pathPrefix,
bucket: client.Bucket(bucketName),
}
}