-
Notifications
You must be signed in to change notification settings - Fork 78
/
websocket.go
86 lines (72 loc) · 1.36 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
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"context"
"errors"
"time"
"github.com/gorilla/websocket"
)
var (
errConnClosed = errors.New("conn closed")
)
func dialWebsocketChan(ctx context.Context, url string) chan []byte {
fallbackMaxSec := 64
initialSec := 1
ch := make(chan []byte)
go func() {
Out:
for {
for initialSec <= fallbackMaxSec {
time.Sleep(time.Duration(initialSec) * time.Second)
cctx, cancel := context.WithCancel(ctx)
if err := dialWebsocketToChan(cctx, url, ch); err == cctx.Err() {
cancel()
break Out
} else if err == errConnClosed {
initialSec = 1
}
cancel()
if initialSec < fallbackMaxSec {
initialSec *= 2
}
}
}
}()
return ch
}
func dialWebsocketToChan(ctx context.Context, url string, ch chan []byte) error {
dialer := &websocket.Dialer{
HandshakeTimeout: 5 * time.Second,
}
conn, _, err := dialer.DialContext(ctx, url, nil)
if err != nil {
return err
}
// ping pong
go func() {
ticker := time.NewTicker(time.Second * 60)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
conn.WriteMessage(websocket.PingMessage, nil)
}
}
}()
Loop:
for {
select {
case <-ctx.Done():
conn.Close()
return ctx.Err()
default:
_, buf, err := conn.ReadMessage()
if err != nil {
break Loop
}
ch <- buf
}
}
return errConnClosed
}