/
fake_listener.go
61 lines (49 loc) · 1.03 KB
/
fake_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
package testing
import (
"errors"
"net"
"sync"
)
// FakeListener implements net.Listener and has an extra method (Provide) that allows
// you to queue a connection to be consumed via Accept.
type FakeListener struct {
ch chan net.Conn
closed bool
mutex *sync.Mutex
}
func NewFakeListener() *FakeListener {
return &FakeListener{
ch: make(chan net.Conn),
mutex: &sync.Mutex{},
}
}
func (fl *FakeListener) Provide(conn net.Conn) error {
fl.mutex.Lock()
defer fl.mutex.Unlock()
if fl.closed {
return errors.New("connection closed")
}
fl.ch <- conn
return nil
}
func (fl *FakeListener) Accept() (net.Conn, error) {
conn, more := <-fl.ch
if more {
return conn, nil
}
return nil, errors.New("connection closed")
}
func (fl *FakeListener) Close() error {
fl.mutex.Lock()
defer fl.mutex.Unlock()
if fl.closed {
return errors.New("connection closed")
}
fl.closed = true
close(fl.ch)
return nil
}
func (*FakeListener) Addr() net.Addr {
a, _ := net.ResolveTCPAddr("tcp", "fake-listener:1111")
return a
}