-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
75 lines (65 loc) · 1.24 KB
/
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
63
64
65
66
67
68
69
70
71
72
73
74
75
//go:build !js
package nodis
import (
"net/http"
"github.com/diiyw/nodis/patch"
"github.com/gorilla/websocket"
)
type Websocket struct {
upgrader websocket.Upgrader
}
func NewWebsocket() *Websocket {
return &Websocket{
upgrader: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
},
}
}
func (ws *Websocket) Publish(addr string, fn func(ChannelConn)) error {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
c, err := ws.upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
fn(&WsConn{c: c})
})
return http.ListenAndServe(addr, nil)
}
func (ws *Websocket) Subscribe(addr string, fn func(patch.Op)) error {
c, _, err := websocket.DefaultDialer.Dial(addr, nil)
if err != nil {
return err
}
for {
_, message, err := c.ReadMessage()
if err != nil {
return err
}
var op patch.Op
op, err = patch.DecodeOp(message)
if err != nil {
return err
}
fn(op)
}
}
type WsConn struct {
c *websocket.Conn
}
func (w *WsConn) Send(op patch.Op) error {
err := w.c.WriteMessage(websocket.BinaryMessage, op.Encode())
if err != nil {
return err
}
return nil
}
func (w *WsConn) Wait() error {
for {
_, _, err := w.c.ReadMessage()
if err != nil {
return err
}
}
}