-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
54 lines (43 loc) · 976 Bytes
/
api.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
package gache
import (
"time"
)
// Set sets the value of the cache.
// If initialization or marshalling fails, it will return an error.
// In memory-only mode it will never fail.
// It will restart the cache's lifetime.
func (g *Cache[T]) Set(value T) error {
g.mutex.Lock()
defer g.mutex.Unlock()
err := g.init()
if err != nil {
return err
}
// update value
g.data.Internal = value
// update time
now := time.Now()
g.data.Time = &now
if g.options.Path != "" {
err = g.save()
}
return err
}
// Get returns the value of the cache.
// If initialization fails, it will return an error.
// In memory-only mode it will never fail.
func (g *Cache[T]) Get() (cached T, expired bool, err error) {
g.mutex.RLock()
defer g.mutex.RUnlock()
err = g.init()
if err != nil {
return
}
// Do not use tryExpire() here, because it modifies the cache, but we RLocked mutex.
if g.isExpired() {
expired = true
return
}
cached = g.data.Internal
return
}