-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
66 lines (59 loc) · 1.46 KB
/
handler.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
package sse
import (
"context"
"fmt"
"net/http"
"sync/atomic"
)
func defaultPermitter(w http.ResponseWriter, r *http.Request) bool {
return r.Header.Get("Accept") == "text/event-stream"
}
// New server-sent event (SSE) handler
func New(log logger) *Handler {
var id atomic.Int64
return &Handler{
Permit: defaultPermitter,
Identity: func(r *http.Request) string {
return fmt.Sprintf("%d", id.Add(1))
},
pub: newPublishers(log),
}
}
type Handler struct {
Permit func(w http.ResponseWriter, r *http.Request) bool
Identity func(r *http.Request) string
pub *publishers
}
var _ http.Handler = (*Handler)(nil)
var _ Publisher = (*Handler)(nil)
func (h *Handler) Publish(ctx context.Context, event *Event) error {
return h.pub.Publish(ctx, event)
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !h.Permit(w, r) {
http.Error(w, "sse: request not permitted", http.StatusForbidden)
return
}
publisher, err := Create(w)
if err != nil {
err = fmt.Errorf("sse: unable to create publisher: %w", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Add the client to the publisher
clientID := h.Identity(r)
eventCh := h.pub.Set(clientID, publisher)
defer h.pub.Remove(clientID)
// Wait for the client to disconnect
ctx := r.Context()
for {
select {
// Send events to the client
case event := <-eventCh:
publisher.Publish(ctx, event)
// Client disconnected
case <-ctx.Done():
return
}
}
}