-
Notifications
You must be signed in to change notification settings - Fork 33
/
certstream.go
77 lines (61 loc) · 1.51 KB
/
certstream.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
package certstream
import (
"time"
"github.com/gorilla/websocket"
"github.com/jmoiron/jsonq"
"github.com/pkg/errors"
)
const (
pingPeriod time.Duration = 15 * time.Second
)
func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
outputStream := make(chan jsonq.JsonQuery)
errStream := make(chan error)
go func() {
for {
c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)
if err != nil {
errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
time.Sleep(5 * time.Second)
continue
}
defer c.Close()
defer close(outputStream)
done := make(chan struct{})
go func() {
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.WriteMessage(websocket.PingMessage, nil)
case <-done:
return
}
}
}()
for {
var v interface{}
c.SetReadDeadline(time.Now().Add(15 * time.Second))
err = c.ReadJSON(&v)
if err != nil {
errStream <- errors.Wrap(err, "Error decoding json frame!")
c.Close()
break
}
jq := jsonq.NewQuery(v)
res, err := jq.String("message_type")
if err != nil {
errStream <- errors.Wrap(err, "Could not create jq object. Malformed json input recieved. Skipping.")
continue
}
if skipHeartbeats && res == "heartbeat" {
continue
}
outputStream <- *jq
}
close(done)
}
}()
return outputStream, errStream
}