forked from pocket-id/analytics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
47 lines (38 loc) · 786 Bytes
/
cache.go
File metadata and controls
47 lines (38 loc) · 786 Bytes
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 (
"sync"
"time"
)
type CacheEntry[T any] struct {
data T
timestamp time.Time
}
type TTLCache[T any] struct {
entries map[string]CacheEntry[T]
mutex sync.RWMutex
ttl time.Duration
}
func NewTTLCache[T any](ttl time.Duration) *TTLCache[T] {
return &TTLCache[T]{
entries: make(map[string]CacheEntry[T]),
ttl: ttl,
}
}
func (c *TTLCache[T]) Get(key string) (T, bool) {
c.mutex.RLock()
defer c.mutex.RUnlock()
entry, exists := c.entries[key]
if !exists || time.Since(entry.timestamp) > c.ttl {
var zero T
return zero, false
}
return entry.data, true
}
func (c *TTLCache[T]) Set(key string, value T) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.entries[key] = CacheEntry[T]{
data: value,
timestamp: time.Now(),
}
}