-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
68 lines (59 loc) · 1.33 KB
/
Copy pathcache.go
File metadata and controls
68 lines (59 loc) · 1.33 KB
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
66
67
68
package main
import (
"fmt"
"sync"
"time"
"github.com/miekg/dns"
cache "github.com/patrickmn/go-cache"
)
var DNSCache *cache.Cache
var DNSCacheInitOnce sync.Once
func initCache() {
DNSCacheInitOnce.Do(func() {
if DNSCache == nil {
DNSCache = cache.New(15*time.Minute, 60*time.Second)
}
})
}
func GetFromCache(question dns.Question) (answer dns.Msg, found bool) {
key := GetDNSKey(question)
if len(key) <= 0 {
found = false
return
}
data, found := DNSCache.Get(key)
if found {
answer = data.(dns.Msg)
return
}
return
}
func GetDNSKey(question dns.Question) string {
return fmt.Sprintf("%s|%d|%d", question.Name, question.Qclass, question.Qtype)
}
func AppendDNSCache(question dns.Question, answer dns.Msg) {
// buffer, _ := json.Marshal(answer)
// log.Println(string(buffer))
if answer.Rcode == dns.RcodeSuccess {
ttl := uint32(10)
for _, header := range answer.Answer {
rr := *(header.Header())
if ttl < rr.Ttl {
ttl = rr.Ttl
}
}
for _, header := range answer.Ns {
rr := *(header.Header())
if ttl < rr.Ttl {
ttl = rr.Ttl
}
}
for _, header := range answer.Extra {
rr := *(header.Header())
if ttl < rr.Ttl {
ttl = rr.Ttl
}
}
DNSCache.Add(GetDNSKey(question), answer, time.Duration(ttl)*time.Second)
}
}