-
Notifications
You must be signed in to change notification settings - Fork 3
/
websocket.go
113 lines (100 loc) · 1.86 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"context"
"sync"
"time"
"github.com/avast/retry-go/v4"
"github.com/gorilla/websocket"
)
type Conn struct {
conn *websocket.Conn
once sync.Once
Ch chan []byte
}
func (c *Conn) Close() error {
c.once.Do(func() {
close(c.Ch)
})
return c.conn.Close()
}
func dialWebsocketToChan(ctx context.Context, url string, ch chan []byte) chan struct{} {
done := make(chan struct{}, 1)
go func() {
for {
var conn *Conn
retry.Do(
func() (err error) {
conn, err = dialWebsocket(ctx, url)
return
},
retry.Attempts(0),
retry.DelayType(func(n uint, err error, config *retry.Config) time.Duration {
println("dial websocket failed", url, n, err.Error())
return retry.BackOffDelay(n, err, config)
}),
retry.RetryIf(func(e error) bool {
return e != context.Canceled
}),
retry.MaxDelay(time.Second*64),
)
Out:
for {
select {
case <-ctx.Done():
done <- struct{}{}
conn.Close()
return
case buf, open := <-conn.Ch:
if !open {
conn.Close()
break Out
}
ch <- buf
}
}
}
}()
return done
}
func dialWebsocket(ctx context.Context, url string) (*Conn, error) {
dialer := &websocket.Dialer{
HandshakeTimeout: 5 * time.Second,
}
conn, _, err := dialer.DialContext(ctx, url, nil)
if err != nil {
return nil, 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)
}
}
}()
ch := make(chan []byte)
c := &Conn{conn: conn, Ch: ch}
go func() {
defer c.Close()
Loop:
for {
select {
case <-ctx.Done():
conn.Close()
return
default:
_, buf, err := conn.ReadMessage()
if err != nil {
break Loop
}
ch <- buf
}
}
}()
return c, nil
}