Skip to content
Snippets Groups Projects

Use config package to handle all controller configurations

Merged Ghost User requested to merge istaester/provide-config-package into develop
Compare and Show latest version
5 files
+ 52
20
Compare changes
  • Side-by-side
  • Inline
Files
5
+ 37
3
@@ -34,6 +34,7 @@ package cmd
import (
"context"
"os"
"path/filepath"
"code.fbi.h-da.de/danet/gosdn"
@@ -80,16 +81,22 @@ func init() {
rootCmd.Flags().StringVar(&csbiOrchestrstor, "csbi-orchestrator", "localhost:55056", "csbi orchestrator address")
}
const (
configHome string = "./configs"
configName string = "gosdn"
configType string = "toml"
)
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath("./configs")
viper.AddConfigPath(configHome)
viper.AddConfigPath("/usr/local/etc/gosdn/")
viper.SetConfigType("toml")
viper.SetConfigName("gosdn")
viper.SetConfigType(configType)
viper.SetConfigName(configName)
}
viper.AutomaticEnv() // read in environment variables that match
@@ -97,6 +104,8 @@ func initConfig() {
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
log.Debug("Using config file:", viper.ConfigFileUsed())
} else {
ensureViperConfigFileExists()
}
viper.SetDefault("socket", ":55055")
@@ -118,3 +127,28 @@ func initConfig() {
log.SetReportCaller(false)
}
}
func ensureFileSystemStoreExists(pathToStore string) error {
emptyString := []byte("")
err := os.WriteFile(pathToStore, emptyString, 0600)
if err != nil {
return err
}
return nil
}
func ensureViperConfigFileExists() {
// Viper will crash if you call 'WriteConfig()' and the file does
// not exists yet.
// Therefore we handle this case here.
// Inspired by //https://github.com/spf13/viper/issues/430#issuecomment-661945101
configPath := filepath.Join(configHome, configName+"."+configType)
if _, err := os.Stat(configPath); os.IsNotExist(err) {
err := ensureFileSystemStoreExists(configPath)
if err != nil {
panic(err)
}
}
}
Loading