From 17918bf85d3e0cfae151f3022d455cb732c1ea17 Mon Sep 17 00:00:00 2001 From: Stein Ivar Berghei Date: Fri, 18 Nov 2022 23:44:10 +0100 Subject: [PATCH] Fix httprouter ws stuff --- routes.go | 21 +++++++++++++++++++++ ws.go | 23 ----------------------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/routes.go b/routes.go index 2d8fcd7..05539b1 100644 --- a/routes.go +++ b/routes.go @@ -6,11 +6,18 @@ import ( "text/template" "github.com/google/uuid" + "github.com/gorilla/websocket" "github.com/julienschmidt/httprouter" ) +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + func init() { app.router = httprouter.New() + app.router.GET("/", app.Index) app.router.GET("/play/:playlist", app.Play) app.router.GET("/reset", app.Reset) @@ -18,6 +25,20 @@ func init() { app.router.ServeFiles("/js/*filepath", http.Dir("js")) app.router.ServeFiles("/css/*filepath", http.Dir("css")) + app.router.HandlerFunc("GET", "/ws", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Printf("WS connection from %v\n", r.RemoteAddr) + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log.Println(err) + return + } + + err = handleWS(conn) + if err != nil { + log.Printf("WS connection closed, %v\n", r.RemoteAddr) + } + })) + go func() { log.Fatal(http.ListenAndServe(":8824", app.router)) }() diff --git a/ws.go b/ws.go index 75a6795..ba964cf 100644 --- a/ws.go +++ b/ws.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "log" - "net/http" "sync" "time" @@ -27,23 +26,6 @@ func init() { } }() - // Since httprouter seems to not like doing websocket stuff, we run a seperate server for it.. for now.. - go func() { - app.mux.HandleFunc("/ws", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Printf("WS connection from %v\n", r.RemoteAddr) - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - log.Println(err) - return - } - - err = handleWS(conn) - if err != nil { - log.Printf("WS connection closed, %v\n", r.RemoteAddr) - } - })) - }() - log.Println("ws.go done.") } @@ -56,11 +38,6 @@ var ws_clients = bcast.NewGroup() var ws_msg chan interface{} var WSMutex = &sync.Mutex{} -var upgrader = websocket.Upgrader{ - ReadBufferSize: 1024, - WriteBufferSize: 1024, -} - func handleWS(c *websocket.Conn) error { memb := ws_clients.Join() defer memb.Close()