-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
269 lines (211 loc) · 6.47 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
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
265
266
267
268
269
package heximage
import (
"bytes"
"encoding/json"
"fmt"
"image"
"image/png"
"io"
"net/http"
"strconv"
"time"
// Import pprof so we can measure runtime performance.
_ "net/http/pprof"
"github.com/disintegration/imaging"
"github.com/garyburd/redigo/redis"
"github.com/gorilla/websocket"
"github.com/rs/cors"
log "github.com/sirupsen/logrus"
"github.com/urfave/negroni"
)
// timeout is the cache timeout used to add to requests to prevent the
// browser from re-requesting the image.
const timeout = 30 * time.Second
// StartServer runs an http server capable of serving requests for the image
// service.
func StartServer(addr string, pool *redis.Pool, conn redis.Conn, corsOrigins []string) error {
mux := http.NewServeMux()
mux.Handle("/api/place/live", HandleLiveConnection(pool, conn))
mux.Handle("/api/place/draw", HandleCreatePixel(pool))
mux.Handle("/api/place/board", HandleGetBoard(pool))
mux.Handle("/api/place/board-bitmap", HandleGetBoardBitmap(pool))
n := negroni.Classic() // Includes some default middlewares
if len(corsOrigins) != 0 {
n.Use(cors.New(cors.Options{
AllowedOrigins: corsOrigins,
}))
}
n.UseHandler(mux)
log.Debugf("Now listening on %s", addr)
return http.ListenAndServe(addr, n)
}
// HandleLiveConnection brokers the websocket connection with redis.
func HandleLiveConnection(pool *redis.Pool, psconn redis.Conn) http.HandlerFunc {
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// This looks wrong, but the origin is checked in the middleware (which
// happens before this handler) and therefore we should just skip this.
return true
},
} // use default options
messages := make(chan []byte)
newClients := make(chan *websocket.Conn)
closingClients := make(chan *websocket.Conn)
// Create the pubsub connection and subscribe.
psc := redis.PubSubConn{Conn: psconn}
psc.Subscribe(updatesKey)
// This routine will keep track of new clients connecting so we know if we
// need to send them data
go func() {
clients := make(map[*websocket.Conn]bool)
for {
select {
case con := <-newClients:
log.Debugf("CML: A new client has connected")
clients[con] = true
case msg := <-messages:
log.Debugf("CML: A new message needs to be sent")
for con := range clients {
if err := con.WriteMessage(websocket.TextMessage, msg); err != nil {
log.Debugf("CML: Writing to a client failed: %s", err.Error())
delete(clients, con)
continue
}
}
case con := <-closingClients:
log.Debugf("CML: A client has disconnected.")
delete(clients, con)
}
}
}()
go func() {
for {
switch n := psc.Receive().(type) {
case redis.Message:
// A new message from Redis, send it to all connected clients.
log.Debugf("RD: New Message: %s", string(n.Data))
messages <- n.Data
case redis.Subscription:
log.Debugf("RD: Subscription: %d", n.Count)
case error:
// An error was encountered while managing the pubsub connection.
log.Debugf("RD: Error: %s", n.Error())
return
}
}
}()
return func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func() {
closingClients <- c
c.Close()
}()
newClients <- c
for {
_, message, err := c.ReadMessage()
if err != nil {
break
}
log.Debugf("WS: New Message: %s", string(message))
var buf = bytes.NewBuffer(message)
var px Pixel
if err := json.NewDecoder(buf).Decode(&px); err != nil {
log.Debugf("WS: Error: %s", err.Error())
continue
}
conn := pool.Get()
if err := SetColour(conn, px); err != nil {
log.Debugf("WS: Error: %s", err.Error())
conn.Close()
continue
}
conn.Close()
}
}
}
// HandleCreatePixel handles creating pixels on the image.
func HandleCreatePixel(pool *redis.Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
conn := pool.Get()
defer conn.Close()
var px Pixel
if err := json.NewDecoder(r.Body).Decode(&px); err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if err := SetColour(conn, px); err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
}
// HandleGetBoard handles serving the board as a png image.
func HandleGetBoard(pool *redis.Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
conn := pool.Get()
defer conn.Close()
img, err := GetImage(conn)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
widthParam := r.URL.Query().Get("w")
if widthParam != "" {
if widthValue, err := strconv.Atoi(widthParam); err == nil {
img = imaging.Resize(img, widthValue, 0, imaging.NearestNeighbor)
}
}
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int64(timeout.Seconds())))
w.Header().Set("Last-Modified", time.Now().String())
enc := png.Encoder{
CompressionLevel: png.BestSpeed,
}
if err := enc.Encode(w, img); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
// HandleGetBoardBitmap handles serving the board as a png image.
func HandleGetBoardBitmap(pool *redis.Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
conn := pool.Get()
defer conn.Close()
img, err := GetImage(conn)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int64(timeout.Seconds())))
w.Header().Set("Last-Modified", time.Now().String())
rimg, ok := img.(*image.RGBA)
if !ok {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
buf := bytes.NewBuffer(rimg.Pix)
if _, err := io.Copy(w, buf); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}