-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathnet.go
64 lines (57 loc) · 1.77 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package dnscache
import (
"context"
"math/rand"
"net"
"time"
)
var randPerm = func(n int) []int {
return rand.Perm(n)
}
type dialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
// DialFunc is a helper function which returns `net.DialContext` function.
// It randomly fetches an IP from the DNS cache and dials it by the given dial
// function. It dials one by one and returns first connected `net.Conn`.
// If it fails to dial all IPs from cache it returns first error. If no baseDialFunc
// is given, it sets default dial function.
//
// You can use returned dial function for `http.Transport.DialContext`.
//
// In this function, it uses functions from `rand` package. To make it really random,
// you MUST call `rand.Seed` and change the value from the default in your application
func DialFunc(resolver *Resolver, baseDialFunc dialFunc) dialFunc {
if baseDialFunc == nil {
// This is same as which `http.DefaultTransport` uses.
baseDialFunc = (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext
}
return func(ctx context.Context, network, addr string) (net.Conn, error) {
h, p, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
// Fetch DNS result from cache.
//
// ctxLookup is only used for cancelling DNS Lookup.
ctxLookup, cancelF := context.WithTimeout(ctx, resolver.lookupTimeout)
defer cancelF()
ips, err := resolver.Fetch(ctxLookup, h)
if err != nil {
return nil, err
}
var firstErr error
for _, randomIndex := range randPerm(len(ips)) {
conn, err := baseDialFunc(ctx, "tcp", net.JoinHostPort(ips[randomIndex].String(), p))
if err == nil {
return conn, nil
}
if firstErr == nil {
firstErr = err
}
}
return nil, firstErr
}
}