Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure default config file is read correctly #22

Merged
merged 1 commit into from
Aug 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 22 additions & 24 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,38 +97,36 @@ func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
configFilePath, exists := os.LookupEnv("INVENTORY_API_CONFIG")
if !exists {
log.Fatal("Environment variable INVENTORY_API_CONFIG is not set")
if configFilePath, exists := os.LookupEnv("INVENTORY_API_CONFIG"); exists {
absPath, err := filepath.Abs(configFilePath)
if err != nil {
log.Fatalf("Failed to resolve absolute path for config file: %v", err)
}
// Set the config file path
viper.SetConfigFile(absPath)
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading INVENTORY_API_CONFIG file, %s", err)
}
} else {
home, err := os.UserHomeDir()
cobra.CheckErr(err)

viper.AddConfigPath(".")
viper.AddConfigPath(home)
viper.SetConfigType("yaml")

viper.SetConfigName("." + Name)
}
absPath, err := filepath.Abs(configFilePath)
if err != nil {
log.Fatalf("Failed to resolve absolute path for config file: %v", err)
}
// Set the config file path
viper.SetConfigFile(absPath)
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading INVENTORY_API_CONFIG file, %s", err)
}

// home, err := os.UserHomeDir()
// cobra.CheckErr(err)
//
// viper.AddConfigPath(".")
// viper.AddConfigPath(home)
// viper.SetConfigType("yaml")
//
// configName := Name
// viper.SetConfigName(configName)
}

viper.SetEnvPrefix(Name)
viper.AutomaticEnv()

if err := viper.ReadInConfig(); err != nil {
panic(err)
// msg := fmt.Sprintf("Using config file: %s", viper.ConfigFileUsed())
// logger.Debug(msg)
} else {
msg := fmt.Sprintf("Using config file: %s", viper.ConfigFileUsed())
logger.Debug(msg)
}

// put the values into the options struct.
Expand Down
Loading