-
Notifications
You must be signed in to change notification settings - Fork 2
/
client_event.go
50 lines (38 loc) · 889 Bytes
/
client_event.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
package salt
import (
"bufio"
"bytes"
"context"
"net/http"
)
type Events struct {
*Client
}
type EventStreamFunc func(Response) error
func (c *Events) Fire(ctx context.Context, tag string, data any) error {
req := Request{
"client": "runner", "fun": "event.send", "tag": tag, "data": data,
}
return c.do(ctx, "POST", "/", req, nil)
}
func (c *Events) Stream(ctx context.Context, fn EventStreamFunc) error {
var prefix = []byte("data: ")
return c.do(ctx, "GET", "events", nil, func(r *http.Response) error {
// Signal to the scanner to terminate when the context is done.
go func() {
<-ctx.Done()
r.Body.Close()
}()
sc := bufio.NewScanner(r.Body)
for sc.Scan() {
data := sc.Bytes()
if !bytes.HasPrefix(data, prefix) {
continue
}
if err := fn(Response(data[len(prefix):])); err != nil {
return err
}
}
return sc.Err()
})
}