-
Notifications
You must be signed in to change notification settings - Fork 1
/
subscribe.go
94 lines (76 loc) · 1.79 KB
/
subscribe.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
package eclair
import (
"fmt"
"net/url"
"time"
"github.com/gorilla/websocket"
)
const (
recoveryInterval = 5 * time.Second
)
func (c *Client) websocketURL() string {
u, _ := url.Parse(c.BaseURL)
u.Scheme = "ws"
u.Path = "/ws"
return u.String()
}
func (c *Client) Subscribe() (<-chan (Message), error) {
ch := make(chan Message)
go func() {
defer close(ch)
for {
conn, _, err := websocket.DefaultDialer.Dial(
c.websocketURL(),
c.settings.AuthHeaders(),
)
if err != nil {
err = fmt.Errorf("error connecting to WebSocket: %v", err)
fmt.Println(err)
time.Sleep(recoveryInterval)
continue
}
func() {
defer conn.Close()
for {
_, msg, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
fmt.Printf("error reading from WebSocket: %v\n", err)
}
return // Exit the inner function to reconnect
}
event, err := UnmarshalEvent(msg)
if err != nil {
fmt.Printf("error unmarshaling event: %v\n", err)
continue
}
ch <- *event
}
}()
}
}()
return ch, nil
}
// FilteredSubscription allow you to subscribe to a specific set of events
// and only receive messages for those, vs a firehose of all of them on the
// websocket
// This is a convenience method that wraps Subscribe and filters the messages
// based on the event type
func (c *Client) FilteredSubscription(evts ...eventType) (<-chan (Message), error) {
ch, err := c.Subscribe()
if err != nil {
return nil, err
}
filteredCh := make(chan Message)
go func() {
defer close(filteredCh)
for msg := range ch {
for _, evt := range evts {
if msg.Type == evt {
filteredCh <- msg
}
}
}
}()
return filteredCh, nil
}