allow multiple websocket connections

This commit is contained in:
andrzej 2024-11-24 15:23:08 +01:00
parent af435cf958
commit 8ef8de0943
3 changed files with 54 additions and 0 deletions

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module go-buzz
go 1.23.2
require github.com/gorilla/websocket v1.5.3

2
go.sum Normal file
View File

@ -0,0 +1,2 @@
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=

47
main.go Normal file
View File

@ -0,0 +1,47 @@
package main
import (
"log"
"net/http"
"sync"
"github.com/gorilla/websocket"
)
type webSocketHandler struct {
upgrader websocket.Upgrader
}
// GLOBALS
var connections int = 0
var wg sync.WaitGroup
func (wsh webSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//upgrade http connection to websocket
connection, err := wsh.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Error while upgrading connection to websocket: %s", err)
return
}
connections++
log.Printf("New websocket connection. There are now %v\n", connections)
wg.Add(1)
go func() {
for {
}
}()
defer connection.Close()
}
func main() {
webSocketHandler := webSocketHandler{
upgrader: websocket.Upgrader{},
}
var port string = "8080"
http.Handle("/", webSocketHandler)
wg.Add(1)
log.Printf("listening on port %s...\n", port)
log.Fatal(http.ListenAndServe("localhost:8080", nil))
wg.Wait()
}