diff options
author | Jan C <jan@ruken.pw> | 2016-03-28 12:30:15 (UTC) |
---|---|---|
committer | Jan C <jan@ruken.pw> | 2016-03-28 12:30:15 (UTC) |
commit | e8f2412efe55c969390168e3ce0b41200f780a1e (patch) | |
tree | 41a0e692d0ded0113394712f750b730c4f4fa864 /cache | |
parent | c7f28c0032163075bd21f899c37ae992e3eece80 (diff) |
cache hinzugefuegt. wird derzeit vom lists und grils modul verwendet. versuch die loadingzeit zu verringern (anscheinend wird im hintergrund auf jeder route der index requested, was ziemlich doof ist).
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 | ||