-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (55 loc) · 1.47 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
package main
import (
"code.google.com/p/go.net/websocket"
"flag"
"html/template"
"log"
"net/http"
"os"
"strings"
)
var (
port = flag.String("port", ":8080", "port")
homeTemplate = template.Must(template.ParseFiles("templates/home.html"))
staticFilePath = "/static/"
handlers = map[string]func(http.ResponseWriter, *http.Request){
"/": homeHandler,
"/static/": staticHandler,
}
)
///
/// main
///
func main() {
// set up a map of routes to handler functions
// set up all handlers
for route, handler := range handlers {
http.HandleFunc(route, handler)
}
http.Handle("/ws", websocket.Handler(wsHandler))
// set up global database connections
setupDBConnections()
defer closeDBConnections()
// start the server after getting either a user-entered or default :port
flag.Parse()
log.Printf("ListenAndServe: starting on localhost%s", *port)
if err := http.ListenAndServe(*port, nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
///
/// handlers
///
func homeHandler(response http.ResponseWriter, request *http.Request) {
// pass the `Host` so the app knows which websocket to connect to
homeTemplate.Execute(response, request.Host)
}
func staticHandler(response http.ResponseWriter, request *http.Request) {
cwd, err := os.Getwd()
if err != nil {
log.Fatal("staticHandler: ", err)
panic(err)
}
filePath := cwd + staticFilePath + strings.SplitN(request.RequestURI, "/", 3)[2]
http.ServeFile(response, request, filePath)
}