76 lines
1.6 KiB
Go
76 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"log/slog"
|
|
"math/rand/v2"
|
|
"os"
|
|
"path"
|
|
"time"
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type InputDb map[int]string
|
|
|
|
func newInputDbFromFile(path string, db *InputDb) {
|
|
file, err := os.ReadFile(path)
|
|
if err != nil {
|
|
slog.Error("Could not open file", "path", path)
|
|
os.Exit(1)
|
|
}
|
|
err = yaml.Unmarshal(file, &db)
|
|
if err != nil {
|
|
slog.Error("Error unmarshaling", "path", path, "error", err)
|
|
} else {
|
|
slog.Info("Reloaded Input", "path", path)
|
|
}
|
|
}
|
|
|
|
func (db InputDb) Lookup(key int) string {
|
|
value, ok := db[key]
|
|
if !ok {
|
|
return "X"
|
|
}
|
|
return value
|
|
}
|
|
|
|
func main() {
|
|
var db InputDb
|
|
done := make(chan struct{}, 1)
|
|
ticker := time.NewTicker(100 * time.Millisecond)
|
|
|
|
watcher, err := fsnotify.NewWatcher()
|
|
if err != nil {
|
|
slog.Error("Could not create Watcher", "error", err)
|
|
}
|
|
defer watcher.Close()
|
|
newInputDbFromFile("input/input.yml", &db)
|
|
slog.Info("Loaded DB", "db", db)
|
|
|
|
err = watcher.Add("input/")
|
|
if err != nil {
|
|
slog.Error("Could not watch path", "path", "input/")
|
|
}
|
|
|
|
go func() {
|
|
for {
|
|
select {
|
|
case t := <-ticker.C:
|
|
key := rand.IntN(9) + 1
|
|
value := db.Lookup(key)
|
|
slog.Info("Got Rand", "key", key, "value", value, "ticker", t)
|
|
case event := <-watcher.Events:
|
|
if event.Has(fsnotify.Write) && event.Name == "input/input.yml" {
|
|
slog.Info("Got Event", "event.name", event.Name, "event.name.base", path.Base(event.Name), "event.name.dir", path.Dir(event.Name), "event.op", event.Op, "watchlist", watcher.WatchList())
|
|
newInputDbFromFile("input/input.yml", &db)
|
|
}
|
|
case err := <-watcher.Errors:
|
|
slog.Error("Could not watch", "error", err)
|
|
}
|
|
}
|
|
}()
|
|
|
|
<-done
|
|
}
|