Debian Codegraph @

memory_listener.go

raw symbols SCIP
1 package memlistener
2
3 import "net"
4 import "errors"
5 import "sync/atomic"
6
7 type MemoryListener struct {
8 connections chan net.Conn
9 state chan int
10 isStateClosed uint32
11 }
12
13 func NewMemoryListener() *MemoryListener {
14 ml := &MemoryListener{}
15 ml.connections = make(chan net.Conn)
16 ml.state = make(chan int)
17 return ml
18 }
19
20 func (ml *MemoryListener) Accept() (net.Conn, error) {
21 select {
22 case newConnection := <-ml.connections:
23 return newConnection, nil
24 case <-ml.state:
25 return nil, errors.New("Listener closed")
26 }
27 }
28
29 func (ml *MemoryListener) Close() error {
30 if atomic.CompareAndSwapUint32(&ml.isStateClosed, 0, 1) {
31 close(ml.state)
32 }
33 return nil
34 }
35
36 func (ml *MemoryListener) Dial(network, addr string) (net.Conn, error) {
37 select {
38 case <-ml.state:
39 return nil, errors.New("Listener closed")
40 default:
41 }
42 //Create an in memory transport
43 serverSide, clientSide := net.Pipe()
44 //Pass half to the server
45 ml.connections <- serverSide
46 //Return the other half to the client
47 return clientSide, nil
48
49 }
50
51 type memoryAddr int
52
53 func (memoryAddr) Network() string {
54 return "memory"
55 }
56
57 func (memoryAddr) String() string {
58 return "local"
59 }
60 func (ml *MemoryListener) Addr() net.Addr {
61 return memoryAddr(0)
62 }