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