From fdcf534c7b0fbb3cdc511cf9f26f16cf677994a6 Mon Sep 17 00:00:00 2001 From: Julio Capote Date: Sun, 8 Jan 2023 09:36:33 -0500 Subject: config validation --- config/config.go | 44 +++++++++++++++++++++++++++++++++++++++++++- main.go | 12 +++++++++--- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/config/config.go b/config/config.go index 4c23ba1..62e7136 100644 --- a/config/config.go +++ b/config/config.go @@ -1,6 +1,11 @@ package config -import "time" +import ( + "fmt" + "os" + "regexp" + "time" +) type Config struct { Domain string @@ -18,3 +23,40 @@ type Handler struct { DedupWindow time.Duration Interval time.Duration } + +func (c *Config) Validate() error { + if c.Domain == "" { + return fmt.Errorf("domain cant be blank") + } + if c.DbPath == "" { + return fmt.Errorf("dbPath cant be blank") + } + // TODO do we care? + if len(c.Handlers) == 0 { + return fmt.Errorf("no [[handlers]] defined, nothing to do") + } + + r, _ := regexp.Compile("[A-Za-z0-9]+") + + for _, handler := range c.Handlers { + if handler.Name == "" { + return fmt.Errorf("handler name cant be blank") + } + + matches := r.FindAllString(handler.Name, -1) + if len(matches) != 1 { + return fmt.Errorf("handler names can only be [A-Za-z0-9]") + } + if handler.Interval == 0 { + return fmt.Errorf("handler %s needs interval", handler.Name) + } + if handler.Exec == "" { + return fmt.Errorf("handler %s exec cant be blank", handler.Name) + } + if _, err := os.Stat(handler.Exec); err != nil { + return fmt.Errorf("handler %s exec %s does not exist or is not readable", handler.Name, handler.Exec) + } + + } + return nil +} diff --git a/main.go b/main.go index b5720b1..d7ab887 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "git.capotej.com/capotej/communique/controller" "git.capotej.com/capotej/communique/http" "git.capotej.com/capotej/communique/models" + "github.com/BurntSushi/toml" "github.com/dgraph-io/badger/v3" "github.com/microcosm-cc/bluemonday" @@ -31,7 +32,12 @@ func main() { if err != nil { log.Fatal(err) } - log.Debugf("Loaded TOML Config: %+v", cfg) + log.Debugf("Loaded config: %+v", cfg) + err = cfg.Validate() + if err != nil { + log.Fatal(err) + } + log.Debugf("Validated Config: %+v", cfg) // DB dbOpts := badger.DefaultOptions(cfg.DbPath) @@ -59,7 +65,7 @@ func main() { persister := models.NewPersister(log, db) // Controller - controller, err := controller.NewController(cfg, persister, log) + registry, err := controller.NewController(cfg, persister, log) if err != nil { log.Fatal(err) } @@ -76,7 +82,7 @@ func main() { // // External Http Server writer := &zapio.Writer{Log: logger, Level: zap.DebugLevel} defer writer.Close() - router := http.NewRouter(controller, log) + router := http.NewRouter(registry, log) mainWg.Add(1) go router.Start(writer) -- cgit v1.2.3