forked from hirokisan/bybit
/
server_websocket.go
62 lines (55 loc) · 1.2 KB
/
server_websocket.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
package testhelper
import (
"log"
"net/http"
"net/http/httptest"
"strings"
"github.com/gorilla/websocket"
)
// NewWebsocketServer :
func NewWebsocketServer(opts ...func(*http.ServeMux)) (*httptest.Server, func()) {
mux := http.NewServeMux()
for _, opt := range opts {
opt(mux)
}
ts := httptest.NewServer(mux)
ts.URL = makeWsProtocol(ts.URL)
return ts, ts.Close
}
var upgrader = websocket.Upgrader{}
// WithWebsocketHandlerOption :
func WithWebsocketHandlerOption(
path string,
respBody []byte,
) func(*http.ServeMux) {
return func(mux *http.ServeMux) {
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, _, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
if err := c.WriteMessage(mt, respBody); err != nil {
log.Println("write:", err)
break
}
}
})
}
}
func makeWsProtocol(u string) string {
if strings.HasPrefix(u, "https") {
return "wss" + strings.TrimPrefix(u, "https")
}
if strings.HasPrefix(u, "http") {
return "ws" + strings.TrimPrefix(u, "http")
}
return u
}