-
Notifications
You must be signed in to change notification settings - Fork 18
/
cache.go
65 lines (55 loc) · 1.31 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
package main
import (
"sync"
"time"
)
type Element struct {
Value *Answer
TimeAdded int64
IsWildcardDomain bool
}
type Cache struct {
elements map[string]Element
egressPolicy string
mutex sync.RWMutex
}
func InitCache(egressPolicy string) Cache {
return Cache{
elements: make(map[string]Element),
egressPolicy: egressPolicy,
}
}
func (cache *Cache) Get(k string) (*Element, bool) {
cache.mutex.RLock()
element, found := cache.elements[k]
if !found {
cache.mutex.RUnlock()
return nil, false
}
if cache.egressPolicy == EgressPolicyAudit || element.IsWildcardDomain {
// TTL is in seconds
// if now minus time added is greater than TTL, return nil, so new DNS request is made
if time.Now().Unix()-element.TimeAdded > int64(element.Value.TTL) {
cache.mutex.RUnlock()
return nil, false
} else {
cache.mutex.RUnlock()
return &element, true
}
} else {
// for block scenario
// return the found value
// a separate thread updates the cache before TTL expires
cache.mutex.RUnlock()
return &element, true
}
}
func (cache *Cache) Set(k string, v *Answer, isWildcardDomain bool) {
cache.mutex.Lock()
cache.elements[k] = Element{
Value: v,
TimeAdded: time.Now().Unix(),
IsWildcardDomain: isWildcardDomain,
}
cache.mutex.Unlock()
}