Fix httprouter ws stuff

Stein Ivar Berghei 2022-11-18 23:44:10 +01:00
parent 2e800bca18
commit 17918bf85d
2 changed files with 21 additions and 23 deletions

View File

@ -6,11 +6,18 @@ import (
"text/template" "text/template"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
) )
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func init() { func init() {
app.router = httprouter.New() app.router = httprouter.New()
app.router.GET("/", app.Index) app.router.GET("/", app.Index)
app.router.GET("/play/:playlist", app.Play) app.router.GET("/play/:playlist", app.Play)
app.router.GET("/reset", app.Reset) app.router.GET("/reset", app.Reset)
@ -18,6 +25,20 @@ func init() {
app.router.ServeFiles("/js/*filepath", http.Dir("js")) app.router.ServeFiles("/js/*filepath", http.Dir("js"))
app.router.ServeFiles("/css/*filepath", http.Dir("css")) 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() { go func() {
log.Fatal(http.ListenAndServe(":8824", app.router)) log.Fatal(http.ListenAndServe(":8824", app.router))
}() }()

23
ws.go
View File

@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"log" "log"
"net/http"
"sync" "sync"
"time" "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.") log.Println("ws.go done.")
} }
@ -56,11 +38,6 @@ var ws_clients = bcast.NewGroup()
var ws_msg chan interface{} var ws_msg chan interface{}
var WSMutex = &sync.Mutex{} var WSMutex = &sync.Mutex{}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(c *websocket.Conn) error { func handleWS(c *websocket.Conn) error {
memb := ws_clients.Join() memb := ws_clients.Join()
defer memb.Close() defer memb.Close()