-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
79 lines (65 loc) 路 1.85 KB
/
main.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
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/namsral/flag"
"log"
"net/http"
)
func serveHome(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
http.ServeFile(w, r, "static/index.html")
}
func serveCreate(w http.ResponseWriter, r *http.Request, hotel *Hotel) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
room, err := hotel.createRoom()
if err != nil {
log.Println("create failed!")
http.Redirect(w, r, "/todo", 301)
return
}
roomName := room.name
http.Redirect(w, r, fmt.Sprintf("/r/%v", roomName), 301)
}
func roomHandler(w http.ResponseWriter, r *http.Request, hotel *Hotel) {
http.ServeFile(w, r, "static/room.html")
}
func main() {
var host, port string
flag.StringVar(&host, "host", "", "http host")
flag.StringVar(&port, "port", "8080", "http port")
flag.Parse()
r := mux.NewRouter()
hotel := newHotel()
r.HandleFunc("/", serveHome).Methods("GET")
r.HandleFunc("/create", func(w http.ResponseWriter, r *http.Request) {
serveCreate(w, r, hotel)
}).Methods("POST")
// normal room handler
r.HandleFunc("/r/{room}", func(w http.ResponseWriter, r *http.Request) {
roomHandler(w, r, hotel)
}).Methods("GET")
// "secure" rooms
r.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) {
roomHandler(w, r, hotel)
}).Methods("GET")
r.HandleFunc("/ws/{room}", hotel.serveHotel)
http.Handle("/", r)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
addr := fmt.Sprintf("%s:%s", host, port)
log.Printf("listening on %s:%s\n", host, port)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}