-
Notifications
You must be signed in to change notification settings - Fork 26
/
router.go
51 lines (42 loc) · 1.02 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
package main
import (
"fmt"
r "github.com/dancannon/gorethink"
"github.com/gorilla/websocket"
"net/http"
)
type Handler func(*Client, interface{})
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
type Router struct {
rules map[string]Handler
session *r.Session
}
func NewRouter(session *r.Session) *Router {
return &Router{
rules: make(map[string]Handler),
session: session,
}
}
func (r *Router) Handle(msgName string, handler Handler) {
r.rules[msgName] = handler
}
func (r *Router) FindHandler(msgName string) (Handler, bool) {
handler, found := r.rules[msgName]
return handler, found
}
func (e *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
socket, err := upgrader.Upgrade(w, r, nil)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, err.Error())
return
}
client := NewClient(socket, e.FindHandler, e.session)
defer client.Close()
go client.Write()
client.Read()
}