-
Notifications
You must be signed in to change notification settings - Fork 0
/
multisse.go
32 lines (29 loc) · 848 Bytes
/
multisse.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
package broadcaster
import (
"net/http"
)
type MultiEventSource[K comparable] interface {
GetKey(*http.Request) (K, error)
GetEventSource(K) (<-chan Event, CancelFunc, error)
}
func NewMultiSSEBroadcaster[K comparable](src MultiEventSource[K], opts ...BroadcasterOption) http.Handler {
source := func(key K) (<-chan Event, CancelFunc, error) {
events, cancel, err := src.GetEventSource(key)
if err != nil {
return nil, nil, err
}
return events, cancel, nil
}
b := NewMultiConverterBroadcaster(source, marshalEvent, opts...)
listen := func(r *http.Request) (<-chan string, error) {
key, err := src.GetKey(r)
if err != nil {
return nil, err
}
l, _, err := b.Listen(key, WithContext(r.Context()))
return l, err
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
serveSSE(listen, w, r)
})
}