44package main
55
66import (
7+ "context"
78 "encoding/json"
89 "errors"
910 "fmt"
1011 "io"
12+ "log"
1113 "math/rand"
1214 "net/http"
1315 "strconv"
1416 "sync"
17+ "time"
1518
19+ "github.com/coder/websocket"
20+ "github.com/coder/websocket/wsjson"
1621 "github.com/pion/webrtc/v4"
1722 "github.com/rs/cors"
1823)
@@ -112,6 +117,7 @@ func main() {
112117 fmt .Printf ("Failed to write response: %s" , err )
113118 }
114119 })
120+ mux .HandleFunc ("/lobbies" , db .lobbies )
115121
116122 fmt .Println ("Server started on port 3000" )
117123 // cors.Default() setup the middleware with default options being
@@ -126,6 +132,29 @@ func main() {
126132 }
127133}
128134
135+ func (db * lobbyDatabase ) lobbies (w http.ResponseWriter , r * http.Request ) {
136+ c , err := websocket .Accept (w , r , nil )
137+ if err != nil {
138+ println ("Failed to accept websocket:" , err .Error ())
139+ }
140+ defer c .CloseNow ()
141+
142+ // Set the context as needed. Use of r.Context() is not recommended
143+ // to avoid surprising behavior (see http.Hijacker).
144+ ctx , cancel := context .WithTimeout (context .Background (), time .Second * 10 )
145+ defer cancel ()
146+
147+ var v any
148+ err = wsjson .Read (ctx , c , & v )
149+ if err != nil {
150+ println ("Failed to read websocket message:" , err .Error ())
151+ }
152+
153+ log .Printf ("received: %v" , v )
154+
155+ c .Close (websocket .StatusNormalClosure , "" )
156+ }
157+
129158func (db * lobbyDatabase ) lobbyHost (res http.ResponseWriter , _ * http.Request ) {
130159 lobbyID := db .makeLobby ()
131160 lobby := db .lobbyList [lobbyID ]
0 commit comments