-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent_stream.go
66 lines (53 loc) · 1017 Bytes
/
event_stream.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
package arlo
import (
"bytes"
"encoding/json"
"log"
"github.com/r3labs/sse"
)
type EventStream struct {
Registered bool
Connected bool
SSEClient *sse.Client
Events chan *sse.Event
Verbose bool
}
func NewEventStream() *EventStream {
return &EventStream{
Events: make(chan *sse.Event),
}
}
func (e *EventStream) Listen() error {
errCh := make(chan error, 1)
go func() {
err := e.SSEClient.SubscribeChan("", e.Events)
if err != nil {
errCh <- err
}
}()
type eventPayload struct {
Status string `json:"status"`
}
for event := range e.Events {
e.verbose(string(event.Event))
e.verbose(string(event.Data))
if event.Data != nil {
ep := &eventPayload{}
b := bytes.NewBuffer(event.Data)
err := json.NewDecoder(b).Decode(ep)
if err != nil {
errCh <- err
break
}
if ep.Status == "connected" {
e.Connected = true
}
}
}
return <-errCh
}
func (e *EventStream) verbose(params ...interface{}) {
if e.Verbose {
log.Println(params...)
}
}