This commit is contained in:
Mikess, Sebastian
2024-07-17 13:47:12 +02:00
commit f38a71802f
4 changed files with 98 additions and 0 deletions

73
cmd/root.go Normal file
View File

@@ -0,0 +1,73 @@
package main
import (
"log/slog"
"math/rand/v2"
"os"
"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(10 * 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/input.yml")
if err != nil {
slog.Error("Could not watch path", "path", "input/input.yml")
}
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, ok := <-watcher.Events:
if !ok {
slog.Error("Could not log Event", "event.name", event.Name, "event.op", event.Op)
}
slog.Info("Got Event", "event.name", event.Name, "event.op", event.Op)
newInputDbFromFile("input/input.yml", &db)
}
}
}()
<-done
}

10
go.mod Normal file
View File

@@ -0,0 +1,10 @@
module git.bitkraken.net/go/pointerreplacer
go 1.22.4
require (
github.com/fsnotify/fsnotify v1.7.0
gopkg.in/yaml.v3 v3.0.1
)
require golang.org/x/sys v0.4.0 // indirect

8
go.sum Normal file
View File

@@ -0,0 +1,8 @@
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

7
input/input.yml Normal file
View File

@@ -0,0 +1,7 @@
---
1: A
2: B
3: C
4: D
5: E
6: F