diff options
Diffstat (limited to 'cache')
-rw-r--r-- | cache/cache.go | 54 |
1 files changed, 27 insertions, 27 deletions
diff --git a/cache/cache.go b/cache/cache.go index f6e5661..9647836 100644 --- a/cache/cache.go +++ b/cache/cache.go | |||
@@ -1,56 +1,56 @@ | |||
1 | package cache | 1 | package cache |
2 | 2 | ||
3 | import ( | 3 | import ( |
4 | "time" | 4 | "log" |
5 | "log" | 5 | "time" |
6 | ) | 6 | ) |
7 | 7 | ||
8 | type CacheItem struct { | 8 | type CacheItem struct { |
9 | Expires time.Time | 9 | Expires time.Time |
10 | Value interface{} | 10 | Value interface{} |
11 | } | 11 | } |
12 | type Cache struct { | 12 | type Cache struct { |
13 | items map[int]CacheItem | 13 | items map[int]CacheItem |
14 | } | 14 | } |
15 | 15 | ||
16 | func New() *Cache { | 16 | func New() *Cache { |
17 | c := &Cache{ make(map[int]CacheItem) } | 17 | c := &Cache{make(map[int]CacheItem)} |
18 | go c.ticker() | 18 | go c.ticker() |
19 | return c | 19 | return c |
20 | } | 20 | } |
21 | 21 | ||
22 | func (c *Cache) ticker() { | 22 | func (c *Cache) ticker() { |
23 | for _ = range time.NewTicker(time.Second * 1).C { | 23 | for _ = range time.NewTicker(time.Second * 1).C { |
24 | t := time.Now() | 24 | t := time.Now() |
25 | for key, item := range c.items { | 25 | for key, item := range c.items { |
26 | if t.Sub(item.Expires) > 0 { | 26 | if t.Sub(item.Expires) > 0 { |
27 | log.Println("cache delete", key) | 27 | log.Println("cache delete", key) |
28 | delete(c.items, key) | 28 | delete(c.items, key) |
29 | } | 29 | } |
30 | } | 30 | } |
31 | } | 31 | } |
32 | } | 32 | } |
33 | 33 | ||
34 | func (c *Cache) Insert(key int, item interface{}) { | 34 | func (c *Cache) Insert(key int, item interface{}) { |
35 | c.items[key] = CacheItem{ time.Now().Add(time.Minute * 15), item } | 35 | c.items[key] = CacheItem{time.Now().Add(time.Minute * 15), item} |
36 | } | 36 | } |
37 | 37 | ||
38 | func (c *Cache) Remove(key int) { | 38 | func (c *Cache) Remove(key int) { |
39 | delete(c.items, key) | 39 | delete(c.items, key) |
40 | } | 40 | } |
41 | 41 | ||
42 | func (c *Cache) Clear() { | 42 | func (c *Cache) Clear() { |
43 | c.items = make(map[int]CacheItem) | 43 | c.items = make(map[int]CacheItem) |
44 | } | 44 | } |
45 | 45 | ||
46 | func (c *Cache) Get(key int) (interface{}, bool) { | 46 | func (c *Cache) Get(key int) (interface{}, bool) { |
47 | if ci, ok := c.items[key]; ok { | 47 | if ci, ok := c.items[key]; ok { |
48 | return ci.Value, true | 48 | return ci.Value, true |
49 | } | 49 | } |
50 | return nil, false | 50 | return nil, false |
51 | } | 51 | } |
52 | 52 | ||
53 | func (c *Cache) Has(key int) bool { | 53 | func (c *Cache) Has(key int) bool { |
54 | _, ok := c.items[key] | 54 | _, ok := c.items[key] |
55 | return ok | 55 | return ok |
56 | } \ No newline at end of file | 56 | } |