Skip to content

Commit

Permalink
Web: share watch results for clients
Browse files Browse the repository at this point in the history
  • Loading branch information
Kashkovsky committed Apr 15, 2022
1 parent 414f456 commit eb3a058
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
Binary file modified hostmonitor
Binary file not shown.
38 changes: 27 additions & 11 deletions web/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"os"
"sync"
"time"

"github.com/Kashkovsky/hostmonitor/core"
"github.com/gorilla/websocket"
Expand All @@ -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)))
Expand All @@ -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")
Expand Down

0 comments on commit eb3a058

Please sign in to comment.