forked from Gavinpub/ws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mockServer.go
93 lines (87 loc) · 1.73 KB
/
mockServer.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
package main
import (
"context"
"net/url"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/slytomcat/ws/server"
)
const mockURL = "ws://localhost:8080/ws"
type mockServer struct {
Close func() error
Received chan string
ToSend chan string
Mode int64
}
func newMockServer(interval time.Duration) *mockServer {
received := make(chan string, 10)
toSend := make(chan string, 10)
ctx, cancel := context.WithCancel(context.Background())
u, _ := url.Parse(mockURL)
s := server.NewServer(u.Host)
m := &mockServer{
Close: func() error {
s.Shutdown(ctx)
cancel()
s.Close()
return nil
},
Received: received,
ToSend: toSend,
Mode: websocket.TextMessage,
}
s.WSHandleFunc(u.Path, func(conn *websocket.Conn) {
defer conn.Close()
if interval != 0 {
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(20*time.Millisecond))
case <-ctx.Done():
return
}
}
}()
}
go func() {
for {
_, msg, err := conn.ReadMessage()
if err != nil {
return
}
received <- string(msg)
}
}()
for {
select {
case <-ctx.Done():
TryCloseNormally(conn, "server going down")
return
case data := <-toSend:
conn.WriteMessage(int(atomic.LoadInt64(&m.Mode)), []byte(data))
}
}
})
errCh := make(chan error, 1)
go func() {
errCh <- s.ListenAndServe()
}()
select {
case err := <-errCh:
panic(err)
case <-time.After(50 * time.Millisecond):
}
return m
}
func newMockConn() *websocket.Conn {
dial := websocket.Dialer{}
conn, _, err := dial.Dial(mockURL, nil)
if err != nil {
panic(err)
}
return conn
}