forked from alexandrevicenzi/go-sse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sse.go
264 lines (208 loc) · 5.48 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package sse
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
)
// Server represents a server sent events server.
type Server struct {
mu sync.RWMutex
options *Options
channels map[string]*Channel
addClient chan *Client
removeClient chan *Client
shutdown chan bool
closeChannel chan string
}
// NewServer creates a new SSE server.
func NewServer(options *Options) *Server {
if options == nil {
options = &Options{
Logger: log.New(os.Stdout, "go-sse: ", log.LstdFlags),
}
}
if options.Logger == nil {
options.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
}
s := &Server{
sync.RWMutex{},
options,
make(map[string]*Channel),
make(chan *Client),
make(chan *Client),
make(chan bool),
make(chan string),
}
go s.dispatch()
return s
}
func (s *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
flusher, ok := response.(http.Flusher)
if !ok {
http.Error(response, "Streaming unsupported.", http.StatusInternalServerError)
return
}
h := response.Header()
if s.options.hasHeaders() {
for k, v := range s.options.Headers {
h.Set(k, v)
}
}
if request.Method == "GET" {
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
var channelName string
if s.options.ChannelNameFunc == nil {
channelName = request.URL.Path
} else {
channelName = s.options.ChannelNameFunc(request)
}
lastEventID := request.Header.Get("Last-Event-ID")
c := newClient(lastEventID, channelName)
s.addClient <- c
closeNotify := request.Context().Done()
go func() {
<-closeNotify
s.removeClient <- c
}()
response.WriteHeader(http.StatusOK)
flusher.Flush()
for msg := range c.send {
msg.retry = s.options.RetryInterval
fmt.Fprintf(response, msg.String())
flusher.Flush()
}
} else if request.Method != "OPTIONS" {
response.WriteHeader(http.StatusMethodNotAllowed)
}
}
// SendMessage broadcast a message to all clients in a channel.
// If channelName is an empty string, it will broadcast the message to all channels.
func (s *Server) SendMessage(channelName string, message *Message) {
if len(channelName) == 0 {
s.options.Logger.Print("broadcasting message to all channels.")
s.mu.RLock()
for _, ch := range s.channels {
ch.SendMessage(message)
}
s.mu.RUnlock()
} else if ch, ok := s.getChannel(channelName); ok {
ch.SendMessage(message)
s.options.Logger.Printf("message sent to channel '%s'.", channelName)
} else {
s.options.Logger.Printf("message not sent because channel '%s' has no clients.", channelName)
}
}
// Restart closes all channels and clients and allow new connections.
func (s *Server) Restart() {
s.options.Logger.Print("restarting server.")
s.close()
}
// Shutdown performs a graceful server shutdown.
func (s *Server) Shutdown() {
s.shutdown <- true
}
// ClientCount returns the number of clients connected to this server.
func (s *Server) ClientCount() int {
i := 0
s.mu.RLock()
for _, channel := range s.channels {
i += channel.ClientCount()
}
s.mu.RUnlock()
return i
}
// HasChannel returns true if the channel associated with name exists.
func (s *Server) HasChannel(name string) bool {
_, ok := s.getChannel(name)
return ok
}
// GetChannel returns the channel associated with name or nil if not found.
func (s *Server) GetChannel(name string) (*Channel, bool) {
return s.getChannel(name)
}
// Channels returns a list of all channels to the server.
func (s *Server) Channels() []string {
channels := []string{}
s.mu.RLock()
for name := range s.channels {
channels = append(channels, name)
}
s.mu.RUnlock()
return channels
}
// CloseChannel closes a channel.
func (s *Server) CloseChannel(name string) {
s.closeChannel <- name
}
func (s *Server) addChannel(name string) *Channel {
ch := newChannel(name)
s.mu.Lock()
s.channels[ch.name] = ch
s.mu.Unlock()
s.options.Logger.Printf("channel '%s' created.", ch.name)
return ch
}
func (s *Server) removeChannel(ch *Channel) {
s.mu.Lock()
delete(s.channels, ch.name)
s.mu.Unlock()
ch.Close()
s.options.Logger.Printf("channel '%s' closed.", ch.name)
}
func (s *Server) getChannel(name string) (*Channel, bool) {
s.mu.RLock()
ch, ok := s.channels[name]
s.mu.RUnlock()
return ch, ok
}
func (s *Server) close() {
for _, ch := range s.channels {
s.removeChannel(ch)
}
}
func (s *Server) dispatch() {
s.options.Logger.Print("server started.")
for {
select {
// New client connected.
case c := <-s.addClient:
ch, exists := s.getChannel(c.channel)
if !exists {
ch = s.addChannel(c.channel)
}
ch.addClient(c)
s.options.Logger.Printf("new client connected to channel '%s'.", ch.name)
// Client disconnected.
case c := <-s.removeClient:
if ch, exists := s.getChannel(c.channel); exists {
ch.removeClient(c)
s.options.Logger.Printf("client disconnected from channel '%s'.", ch.name)
if ch.ClientCount() == 0 {
s.options.Logger.Printf("channel '%s' has no clients.", ch.name)
s.removeChannel(ch)
}
}
// Close channel and all clients in it.
case channel := <-s.closeChannel:
if ch, exists := s.getChannel(channel); exists {
s.removeChannel(ch)
} else {
s.options.Logger.Printf("requested to close nonexistent channel '%s'.", channel)
}
// Event Source shutdown.
case <-s.shutdown:
s.close()
close(s.addClient)
close(s.removeClient)
close(s.closeChannel)
close(s.shutdown)
s.options.Logger.Print("server stopped.")
return
}
}
}