-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.go
42 lines (36 loc) · 798 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
package main
import (
"sync"
"time"
)
type CacheItem struct {
Result float64
Expiration time.Time
}
type Cache struct {
mu sync.RWMutex
items map[string]CacheItem
}
func NewCache() *Cache {
vLog("cache.go: Creating new cache")
return &Cache{
items: make(map[string]CacheItem),
}
}
func (c *Cache) Set(key string, value float64, duration time.Duration) {
vLog("cache.go: Setting %s to %f", key, value)
c.mu.Lock()
c.items[key] = CacheItem{Result: value, Expiration: time.Now().Add(duration)}
c.mu.Unlock()
}
func (c *Cache) Get(key string) (float64, bool) {
vLog("cache.go: Getting %s", key)
c.mu.RLock()
item, exists := c.items[key]
if !exists || item.Expiration.Before(time.Now()) {
c.mu.RUnlock()
return 0, false
}
c.mu.RUnlock()
return item.Result, true
}