-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinapp.go
55 lines (47 loc) · 1.17 KB
/
inapp.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
package cache
import (
"context"
"errors"
"reflect"
"sync"
"time"
)
type InApp struct {
sm sync.Map
}
// Item is a struct denoting the format in which any object is stored in In-APP Cache. It contains the object along with an expiration time.
type Item struct {
object interface{}
expiration time.Time
}
func NewInApp() Storage {
return InApp{sm: sync.Map{}}
}
func (i InApp) GetName() string {
return "InApp"
}
func (i InApp) Read(ctx context.Context, key string, opType reflect.Type) (interface{}, error) {
currTime := time.Now()
result, ok := i.sm.Load(key)
if !ok {
return nil, errors.New("cache miss")
}
item, isValid := result.(Item)
if !isValid {
return nil, errors.New("cached entry is not of expected type")
}
expTime := item.expiration
if currTime.After(expTime) {
i.sm.Delete(key)
return nil, errors.New("cache expired")
}
return item.object, nil
}
func (i InApp) Write(ctx context.Context, key string, expiration time.Duration, res interface{}, err error) error {
i.sm.Store(key, Item{object: res, expiration: time.Now().Add(expiration)})
return nil
}
func (i InApp) Delete(ctx context.Context, key string) error {
i.sm.Delete(key)
return nil
}