File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -43,7 +43,12 @@ func httpHandler(w http.ResponseWriter, req *http.Request) {
4343 w .Header ().Set ("Content-Type" , "application/json" )
4444 json .NewEncoder (w ).Encode (resp )
4545
46- client := getClient (clientID )
46+ client , err := WaitForClient (clientID , time .Duration (15 * time .Second ))
47+
48+ if err != nil {
49+ logger .Error ("Could not get client: " , err .Error ())
50+ return
51+ }
4752
4853 reachable , err := tryPing (client , body .IP ,
4954 func () (bool , error ) {
Original file line number Diff line number Diff line change 11package server
22
33import (
4+ "errors"
45 "net/http"
56 "sync"
67 "time"
@@ -61,6 +62,24 @@ func getClient(id string) *websocket.Conn {
6162 return clients [id ]
6263}
6364
65+ func WaitForClient (clientID string , timeout time.Duration ) (* websocket.Conn , error ) {
66+ deadline := time .Now ().Add (timeout )
67+
68+ for time .Now ().Before (deadline ) {
69+ clientsMutex .Lock ()
70+ conn , exists := clients [clientID ]
71+ clientsMutex .Unlock ()
72+
73+ if exists && conn != nil {
74+ return conn , nil
75+ }
76+
77+ time .Sleep (100 * time .Millisecond )
78+ }
79+
80+ return nil , errors .New ("Timed out waiting for client" )
81+ }
82+
6483func sendToClient (client * websocket.Conn , data map [string ]any ) error {
6584 return client .WriteJSON (data )
6685}
You can’t perform that action at this time.
0 commit comments