forked from katakonst/go-dns-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
54 lines (44 loc) · 924 Bytes
/
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
package main
import (
"sync"
"time"
)
type Element struct {
Value interface{}
TimeAdded int64
}
type Cache struct {
elements map[string]Element
mutex sync.RWMutex
expirationTime int64
}
func InitCache(expirationTime int64) Cache {
return Cache{
elements: make(map[string]Element),
expirationTime: expirationTime,
}
}
func (cache *Cache) Get(k string) (interface{}, bool) {
cache.mutex.RLock()
element, found := cache.elements[k]
if !found {
cache.mutex.RUnlock()
return "", false
}
if cache.expirationTime > 0 {
if time.Now().UnixNano()-cache.expirationTime > element.TimeAdded {
cache.mutex.RUnlock()
return "", false
}
}
cache.mutex.RUnlock()
return element.Value, true
}
func (cache *Cache) Set(k string, v interface{}) {
cache.mutex.Lock()
cache.elements[k] = Element{
Value: v,
TimeAdded: time.Now().UnixNano(),
}
cache.mutex.Unlock()
}