-
Notifications
You must be signed in to change notification settings - Fork 3
/
memory_listener.go
62 lines (52 loc) · 1.19 KB
/
memory_listener.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
package memlistener
import "net"
import "errors"
import "sync/atomic"
type MemoryListener struct {
connections chan net.Conn
state chan int
isStateClosed uint32
}
func NewMemoryListener() *MemoryListener {
ml := &MemoryListener{}
ml.connections = make(chan net.Conn)
ml.state = make(chan int)
return ml
}
func (ml *MemoryListener) Accept() (net.Conn, error) {
select {
case newConnection := <-ml.connections:
return newConnection, nil
case <-ml.state:
return nil, errors.New("Listener closed")
}
}
func (ml *MemoryListener) Close() error {
if atomic.CompareAndSwapUint32(&ml.isStateClosed, 0, 1) {
close(ml.state)
}
return nil
}
func (ml *MemoryListener) Dial(network, addr string) (net.Conn, error) {
select {
case <-ml.state:
return nil, errors.New("Listener closed")
default:
}
//Create an in memory transport
serverSide, clientSide := net.Pipe()
//Pass half to the server
ml.connections <- serverSide
//Return the other half to the client
return clientSide, nil
}
type memoryAddr int
func (memoryAddr) Network() string {
return "memory"
}
func (memoryAddr) String() string {
return "local"
}
func (ml *MemoryListener) Addr() net.Addr {
return memoryAddr(0)
}