-
Notifications
You must be signed in to change notification settings - Fork 1
/
hotel.go
81 lines (68 loc) · 1.48 KB
/
hotel.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
package main
import (
"github.com/gorilla/websocket"
"log"
"net/http"
)
const URL_LEN = 16
type Hotel struct {
rooms map[string]*Room
}
func newHotel() *Hotel {
return &Hotel{
rooms: make(map[string]*Room),
}
}
// check a guest in to a room
func (h *Hotel) checkinGuest(id string, room *Room, conn *websocket.Conn) {
guest := &Guest{
id: id,
room: room,
conn: conn,
send: make(chan []byte, 256),
}
guest.room.register <- guest
go guest.writeSocket()
go guest.readSocket()
}
func (h *Hotel) prepareRoom(roomName string) *Room {
log.Printf("prepared new room %s", roomName)
room := newRoom(roomName)
h.rooms[roomName] = room
go h.reservation(room)
return room
}
// Generate a cryptographically random URL to use for the room name
// along with the room.
func (h *Hotel) createRoom() (*Room, error) {
roomName, err := GenRandString(URL_LEN)
if err != nil {
return nil, err
}
room := h.prepareRoom(roomName)
return room, nil
}
func (h *Hotel) reservation(room *Room) {
room.reserve()
delete(h.rooms, room.name)
log.Printf("unreserved room %s", room.name)
}
func (h *Hotel) serveHotel(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
id := r.URL.Query().Get("id")
if id == "" {
log.Printf("id not given dropping connection")
conn.Close()
return
}
roomName := r.URL.Path
room, ok := h.rooms[roomName]
if !ok {
room = h.prepareRoom(roomName)
}
h.checkinGuest(id, room, conn)
}