aboutsummaryrefslogtreecommitdiff
path: root/cache/cache.go
blob: 9647836624056f543d4b080b77405c69f65958c9 (plain)
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
package cache

import (
	"log"
	"time"
)

type CacheItem struct {
	Expires time.Time
	Value   interface{}
}
type Cache struct {
	items map[int]CacheItem
}

func New() *Cache {
	c := &Cache{make(map[int]CacheItem)}
	go c.ticker()
	return c
}

func (c *Cache) ticker() {
	for _ = range time.NewTicker(time.Second * 1).C {
		t := time.Now()
		for key, item := range c.items {
			if t.Sub(item.Expires) > 0 {
				log.Println("cache delete", key)
				delete(c.items, key)
			}
		}
	}
}

func (c *Cache) Insert(key int, item interface{}) {
	c.items[key] = CacheItem{time.Now().Add(time.Minute * 15), item}
}

func (c *Cache) Remove(key int) {
	delete(c.items, key)
}

func (c *Cache) Clear() {
	c.items = make(map[int]CacheItem)
}

func (c *Cache) Get(key int) (interface{}, bool) {
	if ci, ok := c.items[key]; ok {
		return ci.Value, true
	}
	return nil, false
}

func (c *Cache) Has(key int) bool {
	_, ok := c.items[key]
	return ok
}