File: memory_listener.go

package info (click to toggle)
golang-github-hydrogen18-memlistener 0.0~git20200120.dcc25e7-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 68 kB
  • sloc: makefile: 2
file content (62 lines) | stat: -rw-r--r-- 1,218 bytes parent folder | download
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)
}