forked from r3labs/sse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
87 lines (73 loc) · 1.98 KB
/
http.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package sse
import (
"fmt"
"net/http"
"time"
)
// HTTPHandler serves new connections with events for a given stream ...
func (s *Server) HTTPHandler(w http.ResponseWriter, r *http.Request) {
flusher, err := w.(http.Flusher)
if !err {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
// Get the StreamID from the URL
streamID := r.URL.Query().Get("stream")
if streamID == "" {
http.Error(w, "Please specify a stream!", http.StatusInternalServerError)
return
}
stream := s.getStream(streamID)
if stream == nil && !s.AutoStream {
http.Error(w, "Stream not found!", http.StatusInternalServerError)
return
} else if stream == nil && s.AutoStream {
stream = s.CreateStream(streamID)
}
eventid := r.Header.Get("Last-Event-ID")
if eventid == "" {
eventid = "0"
}
// Create the stream subscriber
sub := stream.addSubscriber(eventid)
defer sub.close()
notify := w.(http.CloseNotifier).CloseNotify()
go func() {
<-notify
sub.close()
}()
// Push events to client
for {
select {
case ev, ok := <-sub.connection:
if !ok {
return
}
// If the data buffer is an empty string abort.
if len(ev.Data) == 0 {
break
}
// if the event has expired, dont send it
if s.EventTTL != 0 && time.Now().After(ev.timestamp.Add(s.EventTTL)) {
continue
}
fmt.Fprintf(w, "id: %s\n", ev.ID)
fmt.Fprintf(w, "data: %s\n", ev.Data)
if len(ev.Event) > 0 {
fmt.Fprintf(w, "event: %s\n", ev.Event)
}
if len(ev.Retry) > 0 {
fmt.Fprintf(w, "retry: %s\n", ev.Retry)
}
fmt.Fprint(w, "\n")
flusher.Flush()
}
}
}