forked from vfxetc/statuspage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
163 lines (121 loc) · 3.95 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
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
package main
import (
"fmt"
"log"
"net"
"net/http"
)
type Message struct {
IP net.IP
Content []byte
}
type Broker struct {
// Events are pushed to this channel by the main events-gathering routine
Notifier chan Message
// New client connections
newClients chan chan Message
// Closed client connections
closingClients chan chan Message
// Client connections registry
clients map[chan Message]bool
}
func NewServer() (broker *Broker) {
// Instantiate a broker
broker = &Broker{
Notifier: make(chan Message, 1),
newClients: make(chan chan Message),
closingClients: make(chan chan Message),
clients: make(map[chan Message]bool),
}
// Set it running - listening and broadcasting events
go broker.listen()
return
}
func (broker *Broker) ServeHTTP(rw http.ResponseWriter, req *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", "*")
// Each connection registers its own message channel with the Broker's connections registry
messageChan := make(chan Message)
// Signal the broker that we have a new connection
broker.newClients <- messageChan
// Remove this client from the map of connected clients
// when this handler exits.
defer func() {
broker.closingClients <- messageChan
}()
// Listen to connection close and un-register messageChan
notify := rw.(http.CloseNotifier).CloseNotify()
go func() {
<-notify
broker.closingClients <- messageChan
}()
for {
// Write to the ResponseWriter
// Server Sent Events compatible
msg := <-messageChan
fmt.Fprintf(rw, "data: %s %s\n\n", msg.IP, msg.Content)
// Flush the data immediatly instead of buffering it for later.
flusher.Flush()
}
}
func (broker *Broker) listen() {
for {
select {
case s := <-broker.newClients:
// A new client has connected.
// Register their message channel
broker.clients[s] = true
log.Printf("Client added. %d registered clients", len(broker.clients))
case s := <-broker.closingClients:
// A client has dettached and we want to
// stop sending them messages.
delete(broker.clients, s)
log.Printf("Removed client. %d registered clients", len(broker.clients))
case event := <-broker.Notifier:
// We got a new event from the outside!
// Send event to all connected clients
for clientMessageChan, _ := range broker.clients {
clientMessageChan <- event
}
}
}
}
func main() {
static := http.FileServer(http.Dir("static"))
http.Handle("/", static)
broker := NewServer()
http.Handle("/events", broker)
go func() {
addr := net.UDPAddr{
Port: 11804,
IP: net.ParseIP("0.0.0.0"),
}
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
log.Fatal("FATAL ERROR while opening UDP socket:", err)
}
defer conn.Close()
buf := make([]byte, 8192)
for {
n, addr, err := conn.ReadFromUDP(buf)
if err != nil {
log.Println("ERROR while reading UDP socket:", err)
continue
}
msg := Message{addr.IP, buf[0:n]}
broker.Notifier <- msg
}
}()
log.Println("Starting server...")
err := http.ListenAndServe("0.0.0.0:8100", nil)
log.Fatal("FATAL ERROR while serving HTTP:", err)
}