-
Notifications
You must be signed in to change notification settings - Fork 13
/
eventsource.go
77 lines (56 loc) · 1.16 KB
/
eventsource.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 boltz
import (
"bufio"
"bytes"
"encoding/json"
"net/http"
)
var responseDelimiter = []byte{':', ' '}
func streamSwapStatus(url string, events chan *SwapStatusResponse, stopListening chan bool) error {
handleError := make(chan error)
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "text/event-stream")
var res *http.Response
go func() {
res, err = client.Do(req)
if err != nil {
handleError <- err
return
}
reader := bufio.NewReader(res.Body)
var currentEvent *SwapStatusResponse
for {
line, err := reader.ReadBytes('\n')
if err != nil {
handleError <- err
return
}
split := bytes.Split(line, responseDelimiter)
currentEvent = &SwapStatusResponse{}
if string(split[0]) == "data" {
data := bytes.TrimSpace(split[1])
err = json.Unmarshal(data, currentEvent)
if err != nil {
handleError <- err
return
}
events <- currentEvent
}
}
}()
for {
select {
case err = <-handleError:
return err
case <-stopListening:
if res != nil {
_ = res.Body.Close()
}
return nil
}
}
}