-
Notifications
You must be signed in to change notification settings - Fork 52
/
sse.go
211 lines (178 loc) · 3.66 KB
/
sse.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package znet
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"strconv"
"time"
"github.com/sohaha/zlsgo/zstring"
)
type SSE struct {
ctx context.Context
events chan *sseEvent
net *Context
option *SSEOption
ctxCancel context.CancelFunc
flush func()
lastID string
method string
Comment []byte
}
type sseEvent struct {
ID string
Event string
Comment string
Data []byte
}
func (s *SSE) LastEventID() string {
return s.lastID
}
func (s *SSE) Done() <-chan struct{} {
return s.ctx.Done()
}
func (s *SSE) Stop() {
s.ctxCancel()
}
func (s *SSE) sendComment() {
s.events <- &sseEvent{
Comment: "ping",
}
}
func (s *SSE) Send(id string, data string, event ...string) error {
return s.SendByte(id, zstring.String2Bytes(data), event...)
}
func (s *SSE) Push() {
w := s.net.Writer
r := s.net.Request
s.net.Abort(http.StatusOK)
s.net.write()
s.flush()
ticker := time.NewTicker(time.Duration(s.option.HeartbeatsTime) * time.Millisecond)
defer ticker.Stop()
b := zstring.Buffer(7)
sseFor:
for {
select {
case <-ticker.C:
go s.sendComment()
case <-r.Context().Done():
s.ctxCancel()
break sseFor
case <-s.ctx.Done():
break sseFor
case ev := <-s.events:
if len(ev.Data) > 0 {
if ev.ID != "" {
b.WriteString("id: ")
b.WriteString(ev.ID)
b.WriteString("\n")
}
if bytes.HasPrefix(ev.Data, []byte(":")) {
b.Write(ev.Data)
b.WriteString("\n")
} else {
if bytes.IndexByte(ev.Data, '\n') > 0 {
for _, v := range bytes.Split(ev.Data, []byte("\n")) {
b.WriteString("data: ")
b.Write(v)
b.WriteString("\n")
}
} else {
b.WriteString("data: ")
b.Write(ev.Data)
b.WriteString("\n")
}
}
if len(ev.Event) > 0 {
b.WriteString("event: ")
b.WriteString(ev.Event)
b.WriteString("\n")
}
if s.option.RetryTime > 0 {
b.WriteString("retry: ")
b.WriteString(strconv.Itoa(s.option.RetryTime))
b.WriteString("\n")
}
}
if len(ev.Comment) > 0 {
b.WriteString(": ")
b.WriteString(ev.Comment)
b.WriteString("\n")
}
b.WriteString("\n")
data := zstring.String2Bytes(b.String())
_, _ = w.Write(data)
s.flush()
b.Reset()
b.Grow(7)
}
}
}
func (s *SSE) SendByte(id string, data []byte, event ...string) error {
if s.ctx.Err() != nil {
return errors.New("client has been closed")
}
ev := &sseEvent{
ID: id,
Data: data,
}
if len(event) > 0 {
ev.Event = event[0]
}
s.events <- ev
return nil
}
type SSEOption struct {
RetryTime int
HeartbeatsTime int
}
func NewSSE(c *Context, opts ...func(lastID string, opts *SSEOption)) *SSE {
id := c.GetHeader("Last-Event-ID")
ctx, cancel := context.WithCancel(context.TODO())
s := &SSE{
lastID: id,
events: make(chan *sseEvent),
net: c,
ctx: ctx,
ctxCancel: cancel,
option: &SSEOption{
RetryTime: 3000,
HeartbeatsTime: 15000,
},
}
for _, opt := range opts {
opt(id, s.option)
}
flusher, _ := s.net.Writer.(http.Flusher)
s.flush = func() {
if c.Request.Context().Err() != nil {
return
}
flusher.Flush()
}
s.net.SetHeader("Content-Type", "text/event-stream")
s.net.SetHeader("Cache-Control", "no-cache")
s.net.SetHeader("Connection", "keep-alive")
c.prevData.Code.Store(http.StatusNoContent)
s.net.Engine.shutdowns = append(s.net.Engine.shutdowns, func() {
s.Stop()
})
return s
}
func (c *Context) Stream(step func(w io.Writer) bool) bool {
w := c.Writer
flusher, _ := w.(http.Flusher)
c.write()
for {
if c.stopHandle.Load() {
return false
}
keepOpen := step(w)
flusher.Flush()
if !keepOpen {
return false
}
}
}