forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
70 lines (58 loc) · 1.12 KB
/
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
67
68
69
70
package sse
import (
"context"
"net/http"
)
// Stream represents an output stream that data can be written to
type Stream interface {
Send(Event)
SentCount() int
Done()
SetLimit(limit int)
IsDone() bool
Err(error)
}
// NewStream creates a new stream against the provided response writer
func NewStream(ctx context.Context, w http.ResponseWriter, r *http.Request) Stream {
result := &stream{ctx, w, r, false, 0, 0}
return result
}
type stream struct {
ctx context.Context
w http.ResponseWriter
r *http.Request
done bool
sent int
limit int
}
func (s *stream) Send(e Event) {
if s.sent == 0 {
ok := WritePreamble(s.ctx, s.w)
if !ok {
s.done = true
return
}
}
WriteEvent(s.ctx, s.w, e)
s.sent++
}
func (s *stream) SentCount() int {
return s.sent
}
func (s *stream) SetLimit(limit int) {
s.limit = limit
}
func (s *stream) Done() {
WriteEvent(s.ctx, s.w, goodbyeEvent)
s.done = true
}
func (s *stream) IsDone() bool {
if s.limit == 0 {
return s.done
}
return s.done || s.sent >= s.limit
}
func (s *stream) Err(err error) {
WriteEvent(s.ctx, s.w, Event{Error: err})
s.done = true
}