-
Notifications
You must be signed in to change notification settings - Fork 0
/
clevercache.go
82 lines (61 loc) · 2.07 KB
/
clevercache.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
package clevercache
import (
gctx "code.google.com/p/go.net/context"
"errors"
"log"
)
// The client used to interact with the library and the cacheing engine used
type Client struct {
c Clevercacher // a cacheing library that implements the Clevercacher interface
}
// the key for the cacheing engine stored in the context
var enginekey gctx.Key
type Clevercacher interface {
Get(ctx gctx.Context, key interface{}, params map[string]interface{}) (value interface{}, hit bool, err error)
Set(ctx gctx.Context, key interface{}, value interface{}, params map[string]interface{}) (err error)
Data(ctx gctx.Context, key interface{}, params map[string]interface{}) (value interface{}, err error)
}
func init() {
enginekey = gctx.NewKey("engine")
}
// Return a new client
func New() *Client {
return &Client{}
}
// Return a new context with the required cacheing engine embedded
func NewContext(ctx gctx.Context, engine interface{}) gctx.Context {
return gctx.WithValue(ctx, enginekey, engine)
}
// Get the cacheing engine from the context
func FromContext(ctx gctx.Context) interface{} {
engine := ctx.Value(enginekey)
return engine
}
// add the cacheing engine to the client
func (cl *Client) RegisterCache(c Clevercacher) {
cl.c = c
}
func (cl *Client) Get(ctx gctx.Context, key interface{}, params map[string]interface{}) (value interface{}, err error) {
value, hit, err := cl.c.Get(ctx, key, params)
if hit != true {
// run the cacher in the background
go func(ctx gctx.Context, cl *Client, key interface{}) {
value, err := cl.c.Data(ctx, key, params)
log.Println("value from data - ", value)
if err != nil {
log.Printf("data for key %s cannot be found", key.(string))
}
log.Println("setting data")
err = cl.c.Set(ctx, key, value, params)
}(ctx, cl, key)
return nil, errors.New("no data found - generating new data")
}
if err != nil {
return nil, err
}
return value, err
}
func (cl *Client) Set(ctx gctx.Context, key interface{}, value interface{}, params map[string]interface{}) (err error) {
err = cl.c.Set(ctx, key, value, params)
return
}