-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbadger.go
73 lines (68 loc) · 1.6 KB
/
badger.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
package main
import (
"bufio"
"bytes"
"fmt"
"github.com/dgraph-io/badger/v2"
log "github.com/sirupsen/logrus"
"net/http"
"net/url"
)
type badgerCache struct {
db *badger.DB
}
func newBadgerCache(url *url.URL) (*badgerCache, error) {
path := url.Path
if path == "" {
path = "/tmp/cache-proxy"
}
opt := badger.DefaultOptions(path)
opt.Logger = log.StandardLogger()
db, err := badger.Open(opt)
if err != nil {
return nil, err
}
return &badgerCache{db: db}, nil
}
func (c *badgerCache) get(req *http.Request) (*http.Response, error) {
var res *http.Response
key := []byte("cache-proxy:" + req.URL.String())
err := c.db.View(func(txn *badger.Txn) error {
item, err := txn.Get(key)
if err != nil {
if err != badger.ErrKeyNotFound {
return err
}
return nil
}
return item.Value(func(val []byte) error {
lres, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(val)), req)
if err != nil {
return fmt.Errorf("unable to read response: %w", err)
}
res = lres
return nil
})
})
if err != nil {
return nil, fmt.Errorf("unable to get %q: %w", string(key), err)
}
return res, err
}
func (c *badgerCache) set(req *http.Request, res *http.Response) error {
buf := bytes.Buffer{}
err := res.Write(&buf)
if err != nil {
return fmt.Errorf("unable to write response to buffer: %w", err)
}
key := []byte("cache-proxy:" + req.URL.String())
go func() {
err := c.db.Update(func(txn *badger.Txn) error {
return txn.SetEntry(badger.NewEntry(key, buf.Bytes()).WithTTL(ttl))
})
if err != nil {
log.Warnf("unable to set %q: %v", string(key), err)
}
}()
return nil
}