2019-12-25 21:04:26 +01:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
2020-09-07 22:40:06 +02:00
|
|
|
"container/list"
|
2019-12-25 21:04:26 +01:00
|
|
|
"hash/fnv"
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Cache struct {
|
|
|
|
capacity int
|
|
|
|
mu sync.RWMutex
|
2020-09-05 22:07:35 +02:00
|
|
|
entries map[uint64]Response
|
2020-09-07 22:40:06 +02:00
|
|
|
keys *list.List
|
2019-12-25 21:04:26 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewCache(capacity int) *Cache {
|
|
|
|
if capacity < 0 {
|
|
|
|
capacity = 0
|
|
|
|
}
|
2020-09-07 22:40:06 +02:00
|
|
|
keys := list.New()
|
2019-12-25 21:04:26 +01:00
|
|
|
return &Cache{
|
|
|
|
capacity: capacity,
|
2020-09-05 22:07:35 +02:00
|
|
|
entries: make(map[uint64]Response),
|
2020-09-07 22:40:06 +02:00
|
|
|
keys: keys,
|
2019-12-25 21:04:26 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func key(ip net.IP) uint64 {
|
|
|
|
h := fnv.New64a()
|
|
|
|
h.Write(ip)
|
|
|
|
return h.Sum64()
|
|
|
|
}
|
|
|
|
|
2020-09-05 22:07:35 +02:00
|
|
|
func (c *Cache) Set(ip net.IP, resp Response) {
|
2019-12-25 21:04:26 +01:00
|
|
|
if c.capacity == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
k := key(ip)
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2020-09-07 22:40:06 +02:00
|
|
|
if len(c.entries) == c.capacity {
|
|
|
|
// At capacity. Remove the oldest entry
|
|
|
|
oldest := c.keys.Front()
|
|
|
|
delete(c.entries, oldest.Value.(uint64))
|
|
|
|
c.keys.Remove(oldest)
|
2019-12-25 21:04:26 +01:00
|
|
|
}
|
|
|
|
c.entries[k] = resp
|
2020-09-07 22:40:06 +02:00
|
|
|
c.keys.PushBack(k)
|
2019-12-25 21:04:26 +01:00
|
|
|
}
|
|
|
|
|
2020-09-05 22:07:35 +02:00
|
|
|
func (c *Cache) Get(ip net.IP) (Response, bool) {
|
2019-12-25 21:04:26 +01:00
|
|
|
k := key(ip)
|
|
|
|
c.mu.RLock()
|
|
|
|
defer c.mu.RUnlock()
|
|
|
|
r, ok := c.entries[k]
|
|
|
|
return r, ok
|
|
|
|
}
|