forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 3
/
websocket_dialer.go
88 lines (73 loc) · 1.91 KB
/
websocket_dialer.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
package httpexpect
import (
"bufio"
"net"
"net/http"
"net/http/httptest"
"sync"
"github.com/gorilla/websocket"
)
// 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
},
}
}
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)
}
}()
}
// 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)
}