-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
88 lines (70 loc) · 1.95 KB
/
main.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
package certCache
import (
"context"
"io/ioutil"
"log"
"strings"
"cloud.google.com/go/storage"
"golang.org/x/crypto/acme/autocert"
)
type StorageCache struct {
bucket *storage.BucketHandle
}
func (sc StorageCache) Get(ctx context.Context, key string) ([]byte, error) {
log.Printf("INFO certCache Fetching %+v from cache", key)
contents := []byte{}
obj := sc.bucket.Object(key)
r, err := obj.NewReader(ctx)
if err != nil {
if err == storage.ErrObjectNotExist {
return contents, autocert.ErrCacheMiss
}
log.Printf("ERROR certCache Fetching %+v from cache: %+v", key, err)
return contents, err
}
defer r.Close()
contents, err = ioutil.ReadAll(r)
if err != nil {
log.Printf("ERROR certCache Reading %+v from cache: %+v", key, err)
return contents, err
}
return contents, nil
}
func (sc StorageCache) Put(ctx context.Context, key string, data []byte) error {
log.Printf("INFO certCache Putting %+v into cache", key)
obj := sc.bucket.Object(key)
w := obj.NewWriter(ctx)
if _, err := w.Write(data); err != nil {
log.Printf("ERROR certCache Writing %+v to cache: %+v", key, err)
return err
}
// Close, just like writing a file.
if err := w.Close(); err != nil {
log.Printf("ERROR certCache Closing %+v in cache: %+v", key, err)
return err
}
return nil
}
func (sc StorageCache) Delete(ctx context.Context, key string) error {
log.Printf("INFO certCache Deleting %+v from cache", key)
obj := sc.bucket.Object(key)
return obj.Delete(ctx)
}
func Init(bucketName, project string) (StorageCache, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
log.Fatalf("ERROR certCache Failed to create client: %v", err)
}
sc := StorageCache{
bucket: client.Bucket(bucketName),
}
if err := sc.bucket.Create(ctx, project, nil); err != nil {
if !strings.Contains(err.Error(), "You already own") {
return sc, err
}
} else {
log.Printf("INFO certCache Certs bucket created.")
}
return sc, nil
}