-
Notifications
You must be signed in to change notification settings - Fork 69
/
server.go
115 lines (94 loc) · 2.46 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
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
package main
import (
"fmt"
"log"
"net/http"
"time"
)
type EventServer struct {
notifier chan []byte
accept chan chan []byte
closing chan chan []byte
clients map[chan []byte]bool
}
func NewEventServer() (server *EventServer) {
server = &EventServer{
notifier: make(chan []byte, 1),
accept: make(chan chan []byte),
closing: make(chan chan []byte),
clients: make(map[chan []byte]bool),
}
go server.listen()
return
}
func (server *EventServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Make sure that the writer supports flushing.
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
client := make(chan []byte)
server.accept <- client
defer func() {
server.closing <- client
}()
// Listen to connection close and un-register messageChan
notify := w.(http.CloseNotifier).CloseNotify()
go func() {
<-notify
server.closing <- client
}()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
for {
// Write to the ResponseWriter
// Server Sent Events compatible
fmt.Fprintf(w, "data: %s\n\n", <-client)
// Flush the data immediatly instead of buffering it for later.
flusher.Flush()
}
}
func (server *EventServer) Publish(data string) {
server.notifier <- []byte(data)
}
func (server *EventServer) listen() {
for {
select {
case s := <-server.accept:
// A new client has connected.
// Register their message channel
server.clients[s] = true
log.Printf("Client added. %d registered clients", len(server.clients))
case s := <-server.closing:
// A client has dettached and we want to
// stop sending them messages.
delete(server.clients, s)
log.Printf("Removed client. %d registered clients", len(server.clients))
case event := <-server.notifier:
// We got a new event from the outside!
// Send event to all connected clients
for client, _ := range server.clients {
client <- event
}
}
}
}
func main() {
server := NewEventServer()
go func() {
for {
time.Sleep(50 * time.Millisecond)
go func() {
eventString := fmt.Sprintf("the time is %v", time.Now())
log.Println("Receiving event")
server.Publish(eventString)
}()
}
}()
http.ListenAndServe(":8000", server)
}