forked from thatguystone/cog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
86 lines (74 loc) · 1.63 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
86
package cnet
import (
"fmt"
"net"
"strings"
"time"
)
type cNet struct {
dbgName string
}
// New creates a new networking interface. The debugName is used as the
// RemoteAddr() for channel connections.
func New(debugName string) Net {
return &cNet{
dbgName: debugName,
}
}
func (n *cNet) Dial(addr string, t time.Duration) (net.Conn, error) {
prot, addr := addrSplit(addr, true)
switch prot {
case "ch":
return globalChs.dial(n.dbgName, addr, t)
default:
return net.DialTimeout(prot, addr, t)
}
}
func (n *cNet) HostExists(addr string) bool {
prot, addr := addrSplit(addr, true)
switch prot {
case "ch":
return true
default:
host, _, err := net.SplitHostPort(addr)
if err == nil {
addr = host
}
_, err = net.LookupHost(addr)
return err == nil
}
}
// `prot` is the protocol to use if none is specified in the addr
func (n *cNet) Resolve(prot, addr string) (net.Addr, error) {
parts := strings.Split(addr, "://")
if len(parts) > 1 {
prot, addr = addrSplit(addr, false)
}
switch prot {
case "ch":
return chAddr(addr), nil
case "tcp":
return net.ResolveTCPAddr("tcp", addr)
case "udp":
return net.ResolveUDPAddr("udp", addr)
}
return nil, fmt.Errorf("unsupported protocol: %s", prot)
}
func (n *cNet) Listen(addr string) (net.Listener, error) {
prot, addr := addrSplit(addr, true)
switch prot {
case "ch":
return globalChs.listen(addr)
default:
return net.Listen(prot, addr)
}
}
func (n *cNet) ListenPacket(addr string) (net.PacketConn, error) {
prot, addr := addrSplit(addr, false)
switch prot {
case "ch":
return globalChs.listenPacket(addr)
default:
return net.ListenPacket(prot, addr)
}
}