-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_ws_test.go
98 lines (82 loc) · 1.79 KB
/
connection_ws_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
package jsonrpc_test
import (
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
var upgrader = websocket.Upgrader{}
type testMessage struct {
msgType int
data []byte
}
func newWsServer(push bool) *wsServer {
srv := wsServer{}
srv.push = push
srv.start()
return &srv
}
type wsServer struct {
srv *httptest.Server
testMessages chan testMessage
push bool
closeOnNextMessage atomic.Bool
}
func (t *wsServer) start() {
t.srv = httptest.NewServer(t)
t.testMessages = make(chan testMessage, 16)
}
func (t *wsServer) close() {
t.srv.Close()
}
func (t *wsServer) url(path string) string {
return strings.Replace(t.srv.URL, "http", "ws", 1) + path
}
func (t *wsServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
method := r.Method
if method != http.MethodGet {
http.Error(w, "method not supported", http.StatusMethodNotAllowed)
return
}
path := r.URL.Path
if path != "/ws" {
// return a 200 response indicating no upgrade is available
w.Write([]byte{})
return
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer c.Close()
for {
if t.push {
// notification testing
for msg := range t.testMessages {
err := c.WriteMessage(msg.msgType, msg.data)
if err != nil {
log.WithError(err).Error("failed to write message")
return
}
}
} else {
// normal request -> response
_, _, err := c.ReadMessage()
if err != nil {
log.WithError(err).Error("failed to read message")
return
}
if t.closeOnNextMessage.Load() {
return
}
msg := <-t.testMessages
err = c.WriteMessage(msg.msgType, msg.data)
if err != nil {
log.WithError(err).Error("failed to write message")
return
}
}
}
}