/
server.go
67 lines (53 loc) · 1.38 KB
/
server.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
// Copyright 2017 Axel Etcheverry. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package sse
import (
"net/http"
"time"
)
// LastEventID header
const LastEventID = "Last-Event-ID"
// HandlerFunc type
type HandlerFunc func(ResponseWriter, *http.Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *http.Request) {
f(w, r)
}
// Server struct
type Server struct {
handle HandlerFunc
retryInterval time.Duration
}
// NewServer constructor
func NewServer(handle HandlerFunc) *Server {
return &Server{
handle: handle,
}
}
// SetRetry duration
func (s *Server) SetRetry(duration time.Duration) {
s.retryInterval = duration
}
func (s *Server) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
// Make sure that the writer supports flushing.
flusher, ok := rw.(http.Flusher)
if !ok {
http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "text/event-stream")
rw.Header().Set("Cache-Control", "no-cache")
rw.Header().Set("Connection", "keep-alive")
rw.Header().Set("Access-Control-Allow-Origin", "*")
response := ResponseWriter{
ResponseWriter: rw,
flusher: flusher,
}
if s.retryInterval > 0 {
response.Send(&Retry{
Duration: s.retryInterval,
})
}
s.handle.ServeHTTP(response, r)
}