-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_memory.go
More file actions
68 lines (55 loc) · 1.47 KB
/
cache_memory.go
File metadata and controls
68 lines (55 loc) · 1.47 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
63
64
65
66
67
68
// Copyright 2017-2026 Allow2 Pty Ltd. All rights reserved.
// Use of this source code is governed by the Allow2 API and SDK Licence.
package allow2service
import (
"sync"
"time"
)
// MemoryCache is an in-memory cache with TTL support.
// Thread-safe via sync.RWMutex. Suitable for testing and
// single-process deployments.
type MemoryCache struct {
mu sync.RWMutex
store map[string]memoryCacheEntry
}
// memoryCacheEntry is a cached value with an expiry timestamp.
type memoryCacheEntry struct {
value string
expiresAt int64
}
// NewMemoryCache creates a new MemoryCache.
func NewMemoryCache() *MemoryCache {
return &MemoryCache{
store: make(map[string]memoryCacheEntry),
}
}
// Get retrieves a cached value by key.
func (c *MemoryCache) Get(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
entry, ok := c.store[key]
if !ok {
return "", false
}
if time.Now().Unix() >= entry.expiresAt {
// Don't delete under RLock; just report miss.
// Cleanup happens on next Set or can be done lazily.
return "", false
}
return entry.value, true
}
// Set stores a value in cache with the given TTL in seconds.
func (c *MemoryCache) Set(key, value string, ttlSeconds int) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[key] = memoryCacheEntry{
value: value,
expiresAt: time.Now().Unix() + int64(ttlSeconds),
}
}
// Delete removes a cached value.
func (c *MemoryCache) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.store, key)
}