-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
56 lines (47 loc) · 1.13 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
package eclair
import (
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/tidwall/gjson"
)
func (c *Client) Websocket() (<-chan gjson.Result, error) {
url := strings.Replace(c.baseURL(), "http", "ws", 1) + "/ws"
messages := make(chan gjson.Result)
go func() {
ticker := time.NewTicker(time.Second * 29)
defer ticker.Stop()
defer close(messages)
var err error
var conn *websocket.Conn
go func() {
for {
<-ticker.C
conn.WriteMessage(websocket.PingMessage, nil)
}
}()
retry:
conn, _, err = websocket.DefaultDialer.Dial(url, http.Header{
"Authorization": {c.authorizationHeader()},
})
if err != nil {
log.Println("failed to open websocket connection: " + err.Error())
}
for {
_, message, err := conn.ReadMessage()
if err != nil {
if strings.Contains(err.Error(), "connection reset by peer") {
log.Println("lost websocket to eclair, reconnecting in 5 seconds")
time.Sleep(time.Second * 5)
goto retry
}
log.Println("eclair ws read error: ", err.Error())
return
}
messages <- gjson.ParseBytes(message)
}
}()
return messages, nil
}