diff --git a/api/http_handler.go b/api/http_handler.go new file mode 100644 index 0000000..34ea7af --- /dev/null +++ b/api/http_handler.go @@ -0,0 +1,68 @@ +package api + +import ( + "fmt" + "log" + "net/http" + + "github.com/gorilla/mux" + "github.com/gorilla/websocket" +) + +func ping(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "pong") +} + +func serveStaticFile(fileName string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // TODO: check out why does this even need the request? does it take the file path from it, + // is is possible to manipulate the path like using .. to get around?! + http.ServeFile(w, r, "front_files/"+fileName) + } +} + +func createSession(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, ` + { + "sessionId":"XyZ123" + } + `) +} + +var upgrader = websocket.Upgrader{} + +func signalWS(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + party := vars["party"] + session := vars["session"] + + fmt.Printf("Initiating a websocket, party=%s session=%s\n", party, session) + + conn, err := upgrader.Upgrade(w, r, nil) + + if err != nil { + fmt.Printf("Error initiating websocket, r.URL=%s e=%s", r.URL.String(), err) + } + + websocketSignaler(conn) + +} + +func BuildRouter(listenAddress string) { + mainRouter := mux.NewRouter() + + mainRouter.HandleFunc("/ping", ping) + mainRouter.HandleFunc("/", serveStaticFile("index.html")) + mainRouter.HandleFunc("/index.js", serveStaticFile("index.js")) + mainRouter.HandleFunc("/index.css", serveStaticFile("index.css")) + + api_router := mainRouter.PathPrefix("/api").Subrouter() + api_router.HandleFunc("/session", createSession).Methods("POST") + api_router.HandleFunc("/signal/session/{session}/party/{party}", signalWS) + + err := http.ListenAndServe(listenAddress, mainRouter) + + if err != nil { + log.Fatalf("Error running the web server %s", err) + } +} diff --git a/api/ws_handler.go b/api/ws_handler.go new file mode 100644 index 0000000..e81645d --- /dev/null +++ b/api/ws_handler.go @@ -0,0 +1,21 @@ +package api + +import "github.com/gorilla/websocket" + +func websocketSignaler(conn *websocket.Conn) { + defer conn.Close() + + for { + msgType, msg, err := conn.ReadMessage() + if err != nil { + return + } + + // Let's just echo for now as a placeholder + + err = conn.WriteMessage(msgType, msg) + if err != nil { + return + } + } +} diff --git a/front_files/index.css b/front_files/index.css new file mode 100644 index 0000000..e69de29 diff --git a/front_files/index.html b/front_files/index.html new file mode 100644 index 0000000..cc67b22 --- /dev/null +++ b/front_files/index.html @@ -0,0 +1,3 @@ + + +