-
Notifications
You must be signed in to change notification settings - Fork 7
/
listener_test.go
122 lines (104 loc) · 2.4 KB
/
listener_test.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package proxyprotocol
import (
"log"
"net"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func ExampleNewListener() {
nl, err := net.Listen("tcp", ":80")
if err != nil {
log.Println("ERROR: listen:", err)
return
}
defer nl.Close()
// Wrap listener with 3 second timeout for PROXY header
l := NewListener(nl, 3*time.Second)
for {
c, err := l.Accept()
if err != nil {
log.Println("ERROR: accept:", err)
return
}
// RemoteAddr will be the source address of the PROXY header
log.Println("New connection from:", c.RemoteAddr().String())
}
}
func TestListener_TCPV1(t *testing.T) {
nl, err := net.Listen("tcp", ":0")
assert.NoError(t, err)
defer nl.Close()
l := NewListener(nl, time.Second)
errCh := make(chan error, 2)
connCh := make(chan net.Conn, 1)
go func() {
c, err := net.Dial("tcp", l.Addr().String())
if err != nil {
errCh <- err
return
}
defer c.Close()
HeaderV1{
SrcIP: net.ParseIP("192.168.0.1"),
DestIP: net.ParseIP("192.168.0.2"),
SrcPort: 1234,
DestPort: 5678,
}.WriteTo(c)
}()
go func() {
c, err := l.Accept()
if err != nil {
errCh <- err
}
connCh <- c
}()
timeout := time.NewTimer(time.Second)
select {
case <-timeout.C:
t.Error("timeout waiting for connection")
case err := <-errCh:
t.Error(err)
case c := <-connCh:
assert.Equal(t, "192.168.0.1:1234", c.RemoteAddr().String(), "SrcAddr")
assert.Equal(t, "192.168.0.2:5678", c.LocalAddr().String(), "DestAddr")
}
}
func TestListener_TCPV2(t *testing.T) {
nl, err := net.Listen("tcp", ":0")
assert.NoError(t, err)
defer nl.Close()
l := NewListener(nl, time.Second)
errCh := make(chan error, 2)
connCh := make(chan net.Conn, 1)
go func() {
c, err := net.Dial("tcp", l.Addr().String())
if err != nil {
errCh <- err
return
}
defer c.Close()
HeaderV2{
Command: CmdProxy,
Src: &net.TCPAddr{IP: net.ParseIP("192.168.0.1"), Port: 1234},
Dest: &net.TCPAddr{IP: net.ParseIP("192.168.0.2"), Port: 5678},
}.WriteTo(c)
}()
go func() {
c, err := l.Accept()
if err != nil {
errCh <- err
}
connCh <- c
}()
timeout := time.NewTimer(time.Second)
select {
case <-timeout.C:
t.Error("timeout waiting for connection")
case err := <-errCh:
t.Error(err)
case c := <-connCh:
assert.Equal(t, "192.168.0.1:1234", c.RemoteAddr().String(), "SrcAddr")
assert.Equal(t, "192.168.0.2:5678", c.LocalAddr().String(), "DestAddr")
}
}