-
Notifications
You must be signed in to change notification settings - Fork 63
/
dns.go
72 lines (59 loc) · 1.05 KB
/
dns.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
65
66
67
68
69
70
71
72
package main
import (
"context"
"sort"
"sync"
"time"
"github.com/rs/dnscache"
)
type Lookup func(string) string
type DNSResolver struct {
done chan struct{}
resolver *dnscache.Resolver
wg sync.WaitGroup
}
func NewDnsResolver() *DNSResolver {
r := &DNSResolver{
done: make(chan struct{}, 1),
resolver: &dnscache.Resolver{},
}
r.start()
return r
}
func (c *DNSResolver) start() {
c.wg.Add(1)
defer c.wg.Done()
go func() {
t := time.NewTicker(2 * time.Minute)
defer t.Stop()
for {
select {
case <-c.done:
return
case <-t.C:
c.resolver.Refresh(true)
}
}
}()
}
func (c *DNSResolver) Close() {
c.done <- struct{}{}
c.wg.Wait()
}
// Lookup resolve remote ip to the domains.
func (c *DNSResolver) Lookup(ip string) string {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
addrs, err := c.resolver.LookupAddr(ctx, ip)
if err != nil {
return ip
}
if len(addrs) == 0 {
return ip
}
if len(addrs) == 1 {
return addrs[0]
}
sort.Strings(addrs)
return addrs[0]
}