-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (52 loc) · 1.41 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
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/3cb/ssc"
"github.com/gorilla/mux"
"github.com/boltdb/bolt"
)
func main() {
// start database
db, err := bolt.Open("my.db", 0600, nil)
if err != nil {
log.Fatalf("Unable to open database: %s", err)
}
defer db.Close()
err = createBucket(db, "Spaces")
if err != nil {
log.Fatalf("unable to create bucket: %s", err)
}
pool := ssc.NewPool([]string{}, time.Second*0)
err = pool.Start()
if err != nil {
log.Fatalf("Unable to create socket pool: %s", err)
}
go poll(db, pool)
// routes
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./static/")))
r.PathPrefix("/dist").Handler(http.FileServer(http.Dir("./static")))
r.Handle("/api/spots", spotsHandler(db))
upgrader := &websocket.Upgrader{}
r.Handle("/ws", wsHandler(db, pool, upgrader))
log.Fatal(http.ListenAndServe(":5050", r))
}
func spotsHandler(db *bolt.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
msg := queryDB(db)
w.Write(msg)
})
}
func wsHandler(db *bolt.DB, pool *ssc.Pool, upgrader *websocket.Upgrader) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := pool.AddClientSocket("", upgrader, w, r)
if err != nil {
log.Printf("Unable to create new socket connection")
} else {
log.Printf("New websocket client connected.")
}
})
}