From 869938519211ac277d6300ed3b2a83d68e37ad30 Mon Sep 17 00:00:00 2001 From: mStar aka a person <12024604-mstarongitlab@users.noreply.gitlab.com> Date: Wed, 17 Jan 2024 10:43:49 +0100 Subject: [PATCH] Add config system --- config.toml | 2 ++ config/config.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 config.toml create mode 100644 config/config.go diff --git a/config.toml b/config.toml new file mode 100644 index 0000000..0c74534 --- /dev/null +++ b/config.toml @@ -0,0 +1,2 @@ +[General] +database_path="postgres://linstrom:ugachaka@localhost/linstrom" \ No newline at end of file diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..c651d7a --- /dev/null +++ b/config/config.go @@ -0,0 +1,80 @@ +// Copyright (c) 2024 mStar +// +// Licensed under the EUPL, Version 1.2 +// +// You may not use this work except in compliance with the Licence. +// You should have received a copy of the Licence along with this work. If not, see: +// . +// See the Licence for the specific language governing permissions and limitations under the Licence. +// + +package config + +import ( + "flag" + "os" + + "github.com/BurntSushi/toml" + "github.com/kelseyhightower/envconfig" + log "github.com/sirupsen/logrus" +) + +type CLIArguments struct { + // Path to a config file + ConfigFile string + // Path to a postgres database + // Nil if not provided + DbPath *string +} + +type Config struct { + General struct { + DbPath string `envconfig:"database" toml:"database_path"` + } +} + +// Reads arguments passed to the application +func ReadCLIArguments() CLIArguments { + configFlag := flag.String("config", "config.toml", "Path to a config file") + dbFlag := flag.String("db", "", "Path to a postgres database") + + flag.Parse() + + var dbString *string + if *dbFlag != "" { + dbString = dbFlag + } + + return CLIArguments{ + ConfigFile: *configFlag, + DbPath: dbString, + } +} + +// Read a config from the given CLI arguments as well as the config file specified in the cli args (default is config.toml) +func ReadConfig(cliArgs *CLIArguments) Config { + file, err := os.Open(cliArgs.ConfigFile) + if err != nil { + log.Fatalf("Failed to open file %s with error %v. Does it exist?\n", cliArgs.ConfigFile, err) + } + defer file.Close() + + var cfg Config + + decoder := toml.NewDecoder(file) + _, err = decoder.Decode(&cfg) + if err != nil { + log.Fatalf("Failed to parse config file %s with error %v\n", cliArgs.ConfigFile, err) + } + + err = envconfig.Process("", &cfg) + if err != nil { + log.Fatalf("Failed to overwrite config from env. Error %v\n", err) + } + + if cliArgs.DbPath != nil && *cliArgs.DbPath != "" { + cfg.General.DbPath = *cliArgs.DbPath + } + + return cfg +}