-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
47 lines (40 loc) · 833 Bytes
/
cache.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
package main
import (
"reflect"
"sync"
)
type Cache interface {
Get(key string) interface{}
GetType(key string) reflect.Type
Store(key string, data interface{}) error
}
type InMemoryCache struct {
store map[string]interface{}
mutex sync.RWMutex
}
func (i *InMemoryCache) init() {
i.mutex.Lock()
defer i.mutex.Unlock()
if i.store == nil {
i.store = make(map[string]interface{})
}
}
func (i *InMemoryCache) Get(key string) interface{} {
i.init()
i.mutex.RLock()
defer i.mutex.RUnlock()
return i.store[key]
}
func (i *InMemoryCache) GetType(key string) reflect.Type {
i.init()
i.mutex.RLock()
defer i.mutex.RUnlock()
return reflect.TypeOf(i.store[key])
}
func (i *InMemoryCache) Store(key string, data interface{}) error {
i.init()
i.mutex.Lock()
defer i.mutex.Unlock()
i.store[key] = data
return nil
}