-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathnet.go
More file actions
105 lines (88 loc) · 1.66 KB
/
Copy pathnet.go
File metadata and controls
105 lines (88 loc) · 1.66 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package testutil
import (
"context"
"net"
"sync"
"golang.org/x/xerrors"
)
type Addr struct {
network string
addr string
}
func NewAddr(network, addr string) Addr {
return Addr{network, addr}
}
func (a Addr) Network() string {
return a.network
}
func (a Addr) Address() string {
return a.addr
}
func (a Addr) String() string {
return a.network + "|" + a.addr
}
type InProcNet struct {
sync.Mutex
listeners map[Addr]*inProcListener
}
type inProcListener struct {
c chan net.Conn
n *InProcNet
a Addr
o sync.Once
}
func NewInProcNet() *InProcNet {
return &InProcNet{listeners: make(map[Addr]*inProcListener)}
}
func (n *InProcNet) Listen(network, address string) (net.Listener, error) {
a := Addr{network, address}
n.Lock()
defer n.Unlock()
if _, ok := n.listeners[a]; ok {
return nil, xerrors.New("busy")
}
l := newInProcListener(n, a)
n.listeners[a] = l
return l, nil
}
func (n *InProcNet) Dial(ctx context.Context, a Addr) (net.Conn, error) {
n.Lock()
defer n.Unlock()
l, ok := n.listeners[a]
if !ok {
return nil, xerrors.Errorf("nothing listening on %s", a)
}
x, y := net.Pipe()
select {
case <-ctx.Done():
return nil, ctx.Err()
case l.c <- x:
return y, nil
}
}
func newInProcListener(n *InProcNet, a Addr) *inProcListener {
return &inProcListener{
c: make(chan net.Conn),
n: n,
a: a,
}
}
func (l *inProcListener) Accept() (net.Conn, error) {
c, ok := <-l.c
if !ok {
return nil, net.ErrClosed
}
return c, nil
}
func (l *inProcListener) Close() error {
l.o.Do(func() {
l.n.Lock()
defer l.n.Unlock()
delete(l.n.listeners, l.a)
close(l.c)
})
return nil
}
func (l *inProcListener) Addr() net.Addr {
return l.a
}