-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
71 lines (59 loc) · 1.4 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package httphealth
import (
"errors"
"fmt"
"time"
)
type Cache struct {
Entries map[string]CacheEntry
}
type CacheEntry struct {
Name string
Response CheckResponse
Ttl int64
Created int64
}
func (e *CacheEntry) Expires() int64 {
return e.Created + e.Ttl
}
func (e *CacheEntry) ValidFor() int64 {
return e.Expires() - time.Now().Unix()
}
func (c *Cache) Set(name string, resp CheckResponse, ttl int64) {
fmt.Printf("CACHE: Caching %s for %d seconds\n", name, ttl)
entry := CacheEntry{
Name: name,
Response: resp,
Ttl: ttl,
Created: time.Now().Unix(),
}
if c.Entries == nil {
c.Entries = make(map[string]CacheEntry)
}
c.Entries[name] = entry
}
func (c *Cache) Delete(name string) {
// nil-safe
fmt.Printf("CACHE: Removing entry %s\n", name)
delete(c.Entries, name)
}
func (c *Cache) Get(name string) (CheckResponse, int64, error) {
var err error
var validFor int64
resp := CheckResponse{}
if entry, ok := c.Entries[name]; ok {
// Found an entry, check ttl
if entry.ValidFor() > 0 {
// Still valid
fmt.Printf("CACHE: Cache hit for %s, expires in %d\n", name, entry.ValidFor())
return entry.Response, entry.ValidFor(), err
} else {
// Expired
fmt.Printf("CACHE: Cache for %s expired %d ago\n", name, entry.ValidFor())
c.Delete(entry.Name)
}
} else {
fmt.Printf("CACHE: No entry for %s\n", name)
}
return resp, validFor, errors.New("Not found")
}