/
router.go
70 lines (62 loc) · 1.66 KB
/
router.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
package routing
import (
"github.com/gorilla/mux"
"github.com/googollee/go-socket.io"
"github.com/grant/school-of-tech/school-of-tech/ws"
"github.com/Sirupsen/logrus"
"github.com/grant/school-of-tech/school-of-tech/auth"
"net/http"
)
func NewRouter() *mux.Router {
// Setup websocket server
io, err := socketio.NewServer(nil)
if err != nil {
logrus.Fatal(err)
}
wsEventHandlers := make(map[string]ws.SocketHandler)
// Create mux router
router := mux.NewRouter().StrictSlash(true)
// Add routes
for _, route := range routes {
// Apply middleware
var handler http.Handler = route.HandlerFunc
if route.AuthenticationRequired {
handler = auth.AuthenicationHandler(route.HandlerFunc)
}
handler = HTTPLogger(handler)
// Setup router methods
switch route.Type {
case File:
router.Methods(route.Method).Path(route.Path).Handler(handler)
case Directory:
router.Methods(route.Method).PathPrefix(route.PathPrefix).Handler(handler)
case Ws:
if ws.IsSocketIOEvent(route.Path) {
wsEventHandlers[route.Path] = route.SocketHandler
}
case NotFound:
router.NotFoundHandler = handler
}
}
// Setup socket.io routes
io.On(ws.Connection, func(so socketio.Socket) {
if wsEventHandlers[ws.Connection] != nil {
wsEventHandlers[ws.Connection](so, nil)
}
for _, route := range routes {
if !ws.IsSocketIOEvent(route.Path) {
so.On(route.Path, func(i interface{}) {
route.SocketHandler(so, i)
})
}
}
})
io.On(ws.Error, func(so socketio.Socket, err error) {
if wsEventHandlers[ws.Error] != nil {
wsEventHandlers[ws.Error](so, err)
}
logrus.Println("error:", err)
})
router.Path(ws.URL).Handler(io)
return router
}