-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpusher.go
110 lines (86 loc) · 1.7 KB
/
pusher.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
package sse
import (
"bytes"
"io"
"net/http"
"sync"
"time"
)
var ping = &Ping{}
type pusher struct {
w io.Writer
out http.Flusher
mtx sync.Mutex
clearTimeout func()
timeout time.Duration
buffer bytes.Buffer
}
var _ Pusher = &pusher{}
func (p *pusher) Push(msg *Message) error {
return p.push(msg)
}
func (p *pusher) Close() {
p.mtx.Lock()
defer p.mtx.Unlock()
if p.clearTimeout != nil {
p.clearTimeout()
p.clearTimeout = nil
}
}
func (p *pusher) push(enc StringEncoder) error {
p.mtx.Lock()
defer p.mtx.Unlock()
p.buffer.Reset()
enc.EncodeString(&p.buffer)
if p.clearTimeout != nil && p.timeout > 0 {
p.clearTimeout()
p.clearTimeout = setTimeout(p.timeout, p.ping)
}
_, err := p.w.Write(p.buffer.Bytes())
if err != nil {
return err
}
p.out.Flush()
return nil
}
func (p *pusher) ping() {
p.push(ping)
}
func NewPusher(w http.ResponseWriter, timeout time.Duration) (Pusher, error) {
out, ok := w.(http.Flusher)
if !ok {
return nil, http.ErrNotSupported
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
out.Flush()
p := &pusher{
w: w,
out: out,
}
if timeout > 0 {
p.timeout = timeout
p.clearTimeout = setTimeout(p.timeout, p.ping)
}
return p, nil
}
func setTimeout(delay time.Duration, fn func()) func() {
timer := time.NewTimer(delay)
// Create a cancel channel
cancel := make(chan struct{})
go func() {
select {
case <-timer.C:
// Timer expired, execute the function
fn()
case <-cancel:
// Timer was canceled
timer.Stop()
}
}()
// Return the cancel function
return func() {
close(cancel)
}
}