From 076954d8c1b7c3979fa0c3d668c93661a2728865 Mon Sep 17 00:00:00 2001 From: Denys Kashkovskyi Date: Fri, 15 Apr 2022 17:09:27 +0000 Subject: [PATCH] Web: share watch results for clients --- web/server.go | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/web/server.go b/web/server.go index 67eb803..8f3eb46 100644 --- a/web/server.go +++ b/web/server.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "sync" + "time" "github.com/Kashkovsky/hostmonitor/core" "github.com/gorilla/websocket" @@ -20,14 +21,18 @@ type Server struct { port int upgrader *websocket.Upgrader config *core.WatchConfig + results sync.Map } func NewServer(config *core.WatchConfig, port int) Server { var upgrader = websocket.Upgrader{} - return Server{port: port, upgrader: &upgrader, config: config} + results := sync.Map{} + return Server{port: port, upgrader: &upgrader, config: config, results: results} } func (s *Server) Run() { + s.startWatch() + http.HandleFunc("/ws", s.serveWs) useOS := len(os.Args) > 1 && os.Args[1] == "live" http.Handle("/", http.FileServer(getFileSystem(useOS))) @@ -40,21 +45,32 @@ func (s *Server) serveWs(w http.ResponseWriter, r *http.Request) { log.Print("upgrade:", err) return } - defer c.Close() - watcher := core.NewWatcher(s.config) - mu := sync.Mutex{} + s.sendResults(c) +} - watcher.Watch(func(res core.TestResult) { - mu.Lock() - defer mu.Unlock() - err = c.WriteJSON(res) - if err != nil { - log.Println("write:", err) - } +func (s *Server) startWatch() { + watcher := core.NewWatcher(s.config) + go watcher.Watch(func(res core.TestResult) { + s.results.Store(res.Id, res) }) } +func (s *Server) sendResults(c *websocket.Conn) { + for { + s.results.Range(func(_ any, res interface{}) bool { + err := c.WriteJSON(res) + if err != nil { + log.Println("write:", err) + return false + } + return true + }) + + time.Sleep(time.Second) + } +} + func getFileSystem(useOS bool) http.FileSystem { if useOS { log.Print("using live mode")