forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sse.go
70 lines (60 loc) · 1.66 KB
/
sse.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
package render
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
type sse struct {
Data interface{} `json:"data"`
Type string `json:"type"`
}
func (s *sse) String() string {
b, _ := json.Marshal(s)
return fmt.Sprintf("data: %s\n\n", string(b))
}
func (s *sse) Bytes() []byte {
return []byte(s.String())
}
// EventSource is designed to work with JavaScript EventSource objects.
// see https://developer.mozilla.org/en-US/docs/Web/API/EventSource for
// more details
type EventSource struct {
w http.ResponseWriter
fl http.Flusher
}
func (es *EventSource) Write(t string, d interface{}) error {
s := &sse{Type: t, Data: d}
_, err := es.w.Write(s.Bytes())
if err != nil {
return err
}
es.Flush()
return nil
}
// Flush messages down the pipe. If messages aren't flushed they
// won't be sent.
func (es *EventSource) Flush() {
es.fl.Flush()
}
// CloseNotify return true across the channel when the connection
// in the browser has been severed.
func (es *EventSource) CloseNotify() <-chan bool {
return es.w.(http.CloseNotifier).CloseNotify()
}
// NewEventSource returns a new EventSource instance while ensuring
// that the http.ResponseWriter is able to handle EventSource messages.
// It also makes sure to set the proper response heads.
func NewEventSource(w http.ResponseWriter) (*EventSource, error) {
es := &EventSource{w: w}
var ok bool
es.fl, ok = w.(http.Flusher)
if !ok {
return es, errors.New("streaming is not supported")
}
es.w.Header().Set("Content-Type", "text/event-stream")
es.w.Header().Set("Cache-Control", "no-cache")
es.w.Header().Set("Connection", "keep-alive")
es.w.Header().Set("Access-Control-Allow-Origin", "*")
return es, nil
}