|
|
|
@@ -7,6 +7,7 @@ import ( |
|
|
|
"log" |
|
|
|
"net/http" |
|
|
|
"os/signal" |
|
|
|
"strings" |
|
|
|
"sync" |
|
|
|
"syscall" |
|
|
|
"time" |
|
|
|
@@ -71,11 +72,20 @@ func main() { |
|
|
|
r.HandleFunc("/api/settings", controller.SettingsListController(appState, client, ctx)).Methods("GET") |
|
|
|
r.HandleFunc("/api/settings", controller.SettingsEditController(settingsWriter, appState, client, ctx)).Methods("POST") |
|
|
|
|
|
|
|
// r.HandleFunc("/api/beacons/ws", serveWs(appState, ctx)) |
|
|
|
wsHandler := http.HandlerFunc(serveWs(appState, ctx)) |
|
|
|
restApiHandler := handlers.CORS(originsOk, headersOk, methodsOk)(r) |
|
|
|
mainHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
|
|
|
if strings.HasPrefix(r.URL.Path, "/api/beacons/ws") { |
|
|
|
wsHandler.ServeHTTP(w, r) |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
restApiHandler.ServeHTTP(w, r) |
|
|
|
}) |
|
|
|
|
|
|
|
server := http.Server{ |
|
|
|
Addr: cfg.HTTPAddr, |
|
|
|
Handler: handlers.CORS(originsOk, headersOk, methodsOk)(r), |
|
|
|
Handler: mainHandler, |
|
|
|
} |
|
|
|
|
|
|
|
go server.ListenAndServe() |
|
|
|
@@ -119,9 +129,9 @@ func serveWs(appstate *appcontext.AppState, ctx context.Context) http.HandlerFun |
|
|
|
} |
|
|
|
return |
|
|
|
} |
|
|
|
wg.Add(1) |
|
|
|
wg.Add(2) |
|
|
|
go writer(ws, appstate, ctx) |
|
|
|
reader(ws) |
|
|
|
go reader(ws, ctx) |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
@@ -161,17 +171,25 @@ func writer(ws *websocket.Conn, appstate *appcontext.AppState, ctx context.Conte |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
func reader(ws *websocket.Conn) { |
|
|
|
func reader(ws *websocket.Conn, ctx context.Context) { |
|
|
|
defer func() { |
|
|
|
ws.Close() |
|
|
|
wg.Done() |
|
|
|
}() |
|
|
|
ws.SetReadLimit(512) |
|
|
|
ws.SetReadDeadline(time.Now().Add((60 * 9) / 10 * time.Second)) |
|
|
|
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add((60 * 9) / 10 * time.Second)); return nil }) |
|
|
|
for { |
|
|
|
_, _, err := ws.ReadMessage() |
|
|
|
if err != nil { |
|
|
|
break |
|
|
|
fmt.Println("this is called") |
|
|
|
select { |
|
|
|
case <-ctx.Done(): |
|
|
|
fmt.Println("closing websocket reader") |
|
|
|
return |
|
|
|
default: |
|
|
|
_, _, err := ws.ReadMessage() |
|
|
|
if err != nil { |
|
|
|
return |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |