forked from neex/http2smugl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dns_cache.go
64 lines (56 loc) · 1007 Bytes
/
dns_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
59
60
61
62
63
64
package main
import (
"fmt"
"net"
"sync"
)
type DNSCache struct {
m sync.Mutex
cache map[string]*cacheEntry
}
var DefaultDNSCache = &DNSCache{
cache: make(map[string]*cacheEntry),
}
func (c *DNSCache) Lookup(name string) (net.IP, error) {
return c.getEntry(name).lookupAndFill(name)
}
func (c *DNSCache) getEntry(name string) *cacheEntry {
c.m.Lock()
defer c.m.Unlock()
if e, ok := c.cache[name]; ok {
return e
}
e := new(cacheEntry)
c.cache[name] = e
return e
}
type cacheEntry struct {
m sync.Mutex
ip net.IP
}
func (e *cacheEntry) lookupAndFill(name string) (net.IP, error) {
e.m.Lock()
defer e.m.Unlock()
if e.ip != nil {
return e.ip, nil
}
ips, err := net.LookupIP(name)
if err != nil {
return nil, err
}
if len(ips) == 0 {
return nil, fmt.Errorf("no such host: %v", name)
}
var bestIP net.IP
for _, ip := range ips {
ip4 := ip.To4()
if ip4 != nil {
bestIP = ip4
}
if bestIP == nil {
bestIP = ip
}
}
e.ip = bestIP
return bestIP, nil
}