2021-07-22 18:19:21 -04:00
|
|
|
package coordinator
|
2021-07-22 15:37:25 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
|
2021-07-22 18:19:21 -04:00
|
|
|
func Serve(c *Coordinator) {
|
2021-07-22 15:37:25 -04:00
|
|
|
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
|
2021-07-22 18:19:21 -04:00
|
|
|
serveWs(c, w, r)
|
2021-07-22 15:37:25 -04:00
|
|
|
})
|
|
|
|
err := http.ListenAndServe(":7636", nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("ListenAndServe: ", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-22 18:19:21 -04:00
|
|
|
func serveWs(c *Coordinator, w http.ResponseWriter, r *http.Request) {
|
2021-07-22 15:37:25 -04:00
|
|
|
// Upgrade our raw HTTP connection to a websocket based one
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Print("Error during connection upgradation:", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
// The event loop
|
|
|
|
for {
|
2021-07-22 18:19:21 -04:00
|
|
|
var cmd SessionCommand
|
2021-07-22 15:37:25 -04:00
|
|
|
err := conn.ReadJSON(&cmd)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message reading:", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
log.Printf("Received: %s", cmd)
|
2021-07-22 18:19:21 -04:00
|
|
|
resp := c.Coordinate(&cmd)
|
2021-07-23 16:43:39 -04:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
log.Printf("sending: %v", resp)
|
2021-07-22 15:37:25 -04:00
|
|
|
err = conn.WriteJSON(resp)
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Error during message writing:", err)
|
|
|
|
break
|
|
|
|
}
|
2021-07-22 18:19:21 -04:00
|
|
|
if resp.Result == SessionRespLeft {
|
|
|
|
break
|
|
|
|
}
|
2021-07-22 15:37:25 -04:00
|
|
|
}
|
|
|
|
}
|