-
Notifications
You must be signed in to change notification settings - Fork 18
/
net.go
47 lines (40 loc) · 932 Bytes
/
net.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
package dnscache
import (
"context"
"math/rand"
"net"
"time"
)
type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
func DialContext(resolver *Resolver, baseDial DialFunc) DialFunc {
if baseDial == nil {
baseDial = (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext
}
return func(ctx context.Context, network, addr string) (net.Conn, error) {
h, p, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ips, err := resolver.Resolve(ctx, h)
if err != nil {
return nil, err
}
var firstErr error
for _, randomIndex := range randPerm(len(ips)) {
conn, err := baseDial(ctx, network, net.JoinHostPort(ips[randomIndex].String(), p))
if err == nil {
return conn, nil
}
if firstErr == nil {
firstErr = err
}
}
return nil, firstErr
}
}
var randPerm = func(n int) []int {
return rand.Perm(n)
}