-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
85 lines (72 loc) · 2.35 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package net
import (
"net"
"time"
"chain/net/etcdname"
)
var knownNetworks = map[string]bool{
"ip": true,
"ip4": true,
"ip6": true,
"udp": true,
"udp4": true,
"udp6": true,
"tcp": true,
"tcp4": true,
"tcp6": true,
}
// LookupHost looks up the given host using etcd or the local resolver.
// It returns an array of that host's addresses
// See LookupHost in packages chain/net/etcdname and net for more.
func LookupHost(host string) (addrs []string, err error) {
addrs, _, err = lookupHost(host)
return addrs, err
}
// like LookupHost, but also returns the data source.
func lookupHost(host string) (addrs []string, source string, err error) {
// Make sure empty hosts are rejected. See comment in
// $GOROOT/src/net/lookup.go for more.
if host == "" {
return nil, "", &net.DNSError{Err: "no such host", Name: host}
}
if ip := net.ParseIP(host); ip != nil {
return []string{host}, "literal", nil
}
if addrs, err := etcdname.LookupHost(host); err == nil {
return addrs, "etcd", nil
}
addrs, err = net.LookupHost(host)
return addrs, "stdlib", err
}
// Dialer satisfies the interface pq.Dialer, using chain/net/etcdname for
// hostname lookups in addition to the local resolver.
type Dialer net.Dialer
// DialTimeout acts like Dial but takes a timeout. The timeout includes name resolution, if required.
func (d *Dialer) DialTimeout(network, addr string, timeout time.Duration) (net.Conn, error) {
d1 := new(Dialer)
*d1 = *d
d1.Timeout = timeout
return d1.Dial(network, addr)
}
// Dial connects to the address on the named network. Hostname lookup for addr
// uses package etcdname in addition to the local resolver.
// See func Dial for a description of the network and addr parameters.
func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
if knownNetworks[network] {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
addrs, source, err := lookupHost(host)
if err != nil {
return nil, err
}
if source == "etcd" || len(addrs) == 1 {
// net.Dial iterates through the list of all possible addrs, but we don't need to yet.
addr = net.JoinHostPort(addrs[0], port)
}
// Note: If addr didn't come from etcd AND if there were multiple addrs, this will do
// another name lookup inside of net.DialTimeout because addr is still the original value.
}
return (*net.Dialer)(d).Dial(network, addr)
}