-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsse.go
More file actions
42 lines (38 loc) · 777 Bytes
/
Copy pathsse.go
File metadata and controls
42 lines (38 loc) · 777 Bytes
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
package httpserver
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
const DefaultHeartbeatInterval = 15 * time.Second
func WriteData(w http.ResponseWriter, flusher http.Flusher, payload any) error {
b, err := json.Marshal(payload)
if err != nil {
return err
}
if _, err := fmt.Fprintf(w, "data: %s\n\n", b); err != nil {
return err
}
flusher.Flush()
return nil
}
func Heartbeat(ctx context.Context, w http.ResponseWriter, flusher http.Flusher, interval time.Duration) {
if interval <= 0 {
interval = DefaultHeartbeatInterval
}
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if _, err := w.Write([]byte(": ping\n\n")); err != nil {
return
}
flusher.Flush()
}
}
}