-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathhttp_feed_stream.go
85 lines (67 loc) · 1.39 KB
/
http_feed_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package butlerd
import (
"context"
"fmt"
"net/http"
)
type responseWriter interface {
http.ResponseWriter
http.Flusher
}
type httpFeedStream struct {
cid string
w responseWriter
r *http.Request
hh *httpHandler
ctx context.Context
cancel context.CancelFunc
id int64
requestCh chan []byte
}
func (s *httpFeedStream) emit(data string) error {
id := s.id
s.id++
return s.emitMsg(fmt.Sprintf("id: %d\ndata: %s", id, data))
}
var twoLf = []byte{'\n', '\n'}
func (s *httpFeedStream) emitMsg(data string) error {
_, err := s.w.Write([]byte(data))
if err != nil {
return err
}
_, err = s.w.Write(twoLf)
if err != nil {
return err
}
s.w.(http.Flusher).Flush()
return nil
}
func (s *httpFeedStream) Wait(parentCtx context.Context) error {
s.requestCh = make(chan []byte)
s.hh.putFeedStream(s.cid, s)
defer func() {
s.hh.removeFeedStream(s.cid)
if cs, ok := s.hh.getCallStream(s.cid); ok {
cs.cancelWith(424, "Feed closed while server was awaiting response")
}
}()
ctx, cancel := context.WithCancel(parentCtx)
s.ctx = ctx
s.cancel = cancel
defer cancel()
s.w.Header().Set("content-type", "text/event-stream")
s.w.Header().Set("cache-control", "no-cache")
s.w.WriteHeader(200)
err := s.emitMsg("event: open")
if err != nil {
return err
}
for {
select {
case payload := <-s.requestCh:
s.emit(string(payload))
case <-s.ctx.Done():
return nil
}
}
}