linstrom/config/config.go

88 lines
2.3 KiB
Go
Raw Normal View History

2024-01-17 09:43:49 +00:00
// 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:
// <https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12>.
// 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/joho/godotenv"
2024-01-17 09:43:49 +00:00
"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 {
// Path to the postgres db
DbPath string `envconfig:"DATABASE_PATH" toml:"database_path"`
// Whether the server should handle ssl itself
HandleSSL bool `envconfig:"HANDLE_SSL" toml:"handle_ssl"`
// Whether to enable the builtin frontend
EnableUI bool `envconfig:"ENABLE_UI" toml:"enable_ui"`
Domain string `envconfig:"DOMAIN" toml:"domain"`
2024-01-17 09:43:49 +00:00
}
}
// 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)
}
godotenv.Load()
2024-01-17 09:43:49 +00:00
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
}