-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcache.go
59 lines (46 loc) · 998 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
55
56
57
58
package main
import (
"time"
"github.com/miekg/dns"
"errors"
"github.com/golang/groupcache/lru"
)
type Mesg struct {
Msg *dns.Msg
Expire time.Time
}
type Cache interface {
Get(key string) (Msg *dns.Msg, err error)
Set(key string, Msg *dns.Msg) error
Remove(key string)
Length() int
}
type MemoryCache struct {
CacheStorage *lru.Cache
Expire time.Duration
Maxcount int
}
func (c *MemoryCache) Get(key string) (*dns.Msg, error) {
mesg, ok := c.CacheStorage.Get(key)
if !ok {
return nil, errors.New("Key not found")
}
msg := mesg.(Mesg)
if msg.Expire.Before(time.Now()) {
c.Remove(key)
return nil, errors.New("Key expires")
}
return msg.Msg, nil
}
func (c *MemoryCache) Set(key string, msg *dns.Msg) error {
expire := time.Now().Add(c.Expire)
mesg := Mesg{msg, expire}
c.CacheStorage.Add(key, mesg)
return nil
}
func (c *MemoryCache) Remove(key string) {
c.CacheStorage.Remove(key)
}
func (c *MemoryCache) Length() int {
return c.CacheStorage.Len()
}