-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_cache.go
53 lines (42 loc) · 868 Bytes
/
reverse_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
package reverse_cache
import (
"time"
"github.com/aschepis/netfilter/ip"
"github.com/golang/groupcache/lru"
)
type DomainList struct {
Domains []string
}
type ReverseCache struct {
lru *lru.Cache
}
func New(maxEntries int) *ReverseCache {
return &ReverseCache{
lru: lru.New(maxEntries),
}
}
func (c *ReverseCache) Add(ip ip.Addr, domains *DomainList, ttl int) {
if ttl > 0 {
c.lru.Add(ip, domains)
go c.expire(ip, ttl)
}
}
func (c *ReverseCache) Get(ip ip.Addr) (value *DomainList, ok bool) {
iface, ok := c.lru.Get(ip)
if ok {
value = iface.(*DomainList)
}
return
}
func (c *ReverseCache) Remove(ip ip.Addr) {
c.lru.Remove(ip)
}
func (c *ReverseCache) RemoveOldest() {
c.lru.RemoveOldest()
}
func (c *ReverseCache) expire(ip ip.Addr, ttl int) {
select {
case <-time.After(time.Duration(ttl) * time.Second):
c.lru.Remove(ip)
}
}