-
Notifications
You must be signed in to change notification settings - Fork 0
/
sselistener.go
124 lines (109 loc) · 2.38 KB
/
sselistener.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package broadcaster
import (
"bufio"
"context"
"errors"
"io"
"mime"
"net/http"
"strings"
)
func ListenSSE(ctx context.Context, url string, opts ...SSEListenerOption) (<-chan Event, error) {
slo := defaultSSEListenerOptions
for _, opt := range opts {
opt(&slo)
}
r, err := doRequest(ctx, url, &slo)
if err != nil {
return nil, err
}
events := make(chan Event, slo.bufSize)
go func() {
defer r.Close()
defer close(events)
var builder sseEventBuilder
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
if e := builder.addLine(line); e != nil {
events <- e
}
}
if err := scanner.Err(); err != nil {
events <- errorEvent(err.Error())
}
}()
return events, nil
}
type sseEventBuilder struct {
name string
data string
}
func (b *sseEventBuilder) addLine(line string) Event {
if len(line) == 0 {
if len(b.name) > 0 || len(b.data) > 0 {
e := &textEvent{name: b.name, data: b.data}
b.reset()
return e
}
return nil
}
prefix, value, ok := strings.Cut(line, ": ")
if !ok {
return errorEvent("malformed line: " + line)
}
switch prefix {
case "event":
if len(b.data) > 0 {
return errorEvent("event name sent after data: " + value)
}
b.name = value
case "", "id", "retry":
case "data":
if len(b.data) > 0 {
b.data += "\n" + value
} else {
b.data = value
}
default:
return errorEvent("malformed line: " + line)
}
return nil
}
func (b *sseEventBuilder) reset() {
b.name = ""
b.data = ""
}
type textEvent struct {
name string
data string
}
func (e textEvent) Read() (name, data string) {
return e.name, e.data
}
func errorEvent(data string) Event {
return &textEvent{name: "error", data: data}
}
func doRequest(ctx context.Context, url string, slo *sseListenerOptions) (io.ReadCloser, error) {
req, err := http.NewRequestWithContext(ctx, slo.method, url, slo.body)
if err != nil {
return nil, err
}
for key, values := range slo.header {
req.Header[key] = values
}
if len(slo.bodyContentType) > 0 {
req.Header.Set("Content-Type", slo.bodyContentType)
}
resp, err := slo.client.Do(req)
if err != nil {
return nil, err
}
respCType := resp.Header.Get("Content-Type")
if parsed, _, _ := mime.ParseMediaType(respCType); parsed != "text/event-stream" {
resp.Body.Close()
return nil, errors.New("bad content type: " + respCType)
}
return resp.Body, nil
}