-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
55 lines (46 loc) · 849 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
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"time"
)
type Bucket struct {
Url string
Refreshed time.Time
Data map[string]interface{}
}
type Cache struct {
ttl time.Duration
table map[string]Bucket
}
func NewCache(timeToLive time.Duration) *Cache {
return &Cache{
ttl: timeToLive,
table: make(map[string]Bucket),
}
}
func (c *Cache) AddOrUpdate(bucket Bucket) {
c.table[bucket.Url] = Bucket{}
c.table[bucket.Url] = bucket
}
func (c *Cache) Remove(url string) {
delete(c.table, url)
}
func (c *Cache) Has(url string) map[string]interface{} {
if hit, ok := c.table[url]; ok {
return hit.Data
}
return nil
}
func (c *Cache) Invalidator() {
for {
if len(c.table) == 0 {
continue
}
func() {
for _, v := range c.table {
if v.Refreshed.Add(c.ttl).Compare(time.Now()) == -1 {
c.Remove(v.Url)
}
}
}()
}
}