-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
62 lines (53 loc) · 1.18 KB
/
Copy pathcache.go
File metadata and controls
62 lines (53 loc) · 1.18 KB
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
package git
import (
"fmt"
)
// Cache represents a caching interface
type Cache interface {
// Put puts value into cache with key and expire time.
Put(key string, val any, timeout int64) error
// Get gets cached value by given key.
Get(key string) any
// IsExist checks if key exists
IsExist(key string) bool
Delete(key string) error
}
var lcache Cache
func Initialize(c Cache) {
lcache = c
}
// GetCache returns the currently configured cache
func GetCache() Cache {
return lcache
}
// Get returns the key value from cache with callback when no key exists in cache
func Get[T any](key string, getFunc func() (T, error)) (T, error) {
var (
empty T
)
if lcache == nil || CacheService.Cache.TTL == 0 {
return getFunc()
}
if !lcache.IsExist(key) {
value, err := getFunc()
if err != nil {
return value, err
}
err = lcache.Put(key, value, CacheService.Cache.TTL.Milliseconds())
if err != nil {
return empty, err
}
}
value := lcache.Get(key)
if v, ok := value.(T); ok {
return v, nil
}
return empty, fmt.Errorf("unsupported cached value type: %v", value)
}
// Remove key from cache
func Remove(key string) {
if lcache == nil {
return
}
_ = lcache.Delete(key)
}