websocket_dialer.go
2.5 KB
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
package httpexpect
import (
"bufio"
"net"
"net/http"
"net/http/httptest"
"sync"
"github.com/gorilla/websocket"
"github.com/valyala/fasthttp"
)
// NewWebsocketDialer produces new websocket.Dialer which dials to bound
// http.Handler without creating a real net.Conn.
func NewWebsocketDialer(handler http.Handler) *websocket.Dialer {
return &websocket.Dialer{
NetDial: func(network, addr string) (net.Conn, error) {
hc := newHandlerConn()
hc.runHandler(handler)
return hc, nil
},
}
}
// NewFastWebsocketDialer produces new websocket.Dialer which dials to bound
// fasthttp.RequestHandler without creating a real net.Conn.
func NewFastWebsocketDialer(handler fasthttp.RequestHandler) *websocket.Dialer {
return &websocket.Dialer{
NetDial: func(network, addr string) (net.Conn, error) {
hc := newHandlerConn()
hc.runFastHandler(handler)
return hc, nil
},
}
}
type handlerConn struct {
net.Conn // returned from dialer
backConn net.Conn // passed to the background goroutine
wg sync.WaitGroup
}
func newHandlerConn() *handlerConn {
dialConn, backConn := net.Pipe()
return &handlerConn{
Conn: dialConn,
backConn: backConn,
}
}
func (hc *handlerConn) Close() error {
err := hc.Conn.Close()
hc.wg.Wait() // wait the background goroutine
return err
}
func (hc *handlerConn) runHandler(handler http.Handler) {
hc.wg.Add(1)
go func() {
defer hc.wg.Done()
recorder := &hijackRecorder{conn: hc.backConn}
for {
req, err := http.ReadRequest(bufio.NewReader(hc.backConn))
if err != nil {
return
}
handler.ServeHTTP(recorder, req)
}
}()
}
func (hc *handlerConn) runFastHandler(handler fasthttp.RequestHandler) {
hc.wg.Add(1)
go func() {
defer hc.wg.Done()
_ = fasthttp.ServeConn(hc.backConn, handler)
}()
}
// hijackRecorder it similar to httptest.ResponseRecorder,
// but with Hijack capabilities.
//
// Original idea is stolen from https://github.com/posener/wstest
type hijackRecorder struct {
httptest.ResponseRecorder
conn net.Conn
}
// Hijack the connection for caller.
//
// Implements http.Hijacker interface.
func (r *hijackRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
rw := bufio.NewReadWriter(bufio.NewReader(r.conn), bufio.NewWriter(r.conn))
return r.conn, rw, nil
}
// WriteHeader write HTTP header to the client and closes the connection
//
// Implements http.ResponseWriter interface.
func (r *hijackRecorder) WriteHeader(code int) {
resp := http.Response{StatusCode: code, Header: r.Header()}
_ = resp.Write(r.conn)
}