You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.2 KiB
Go

// package Config wraps the viper library to setup/manage files for FRMS
package config
import (
"FRMS/internal/pkg/logging"
"fmt"
"os"
"github.com/spf13/viper"
)
// LoadConfig loads the file at path/file into a viper object
// Expects config file to be yaml
func LoadConfig(file, path, ext string) (*viper.Viper, error) {
logging.Debug(logging.DStart, "CON Loading config for %s", file)
config := viper.New()
configFile := fmt.Sprintf("%s/%s.%s", path, file, ext)
config.SetConfigName(file)
config.AddConfigPath(path)
config.SetConfigType(ext)
// Sets env vars
config.AutomaticEnv()
// create config directory if it doesn't exist
if err := os.MkdirAll(path, 0750); err != nil && !os.IsExist(err) {
return config, err
}
// attempt to create an empty config incase it doesn't exist
if err := config.SafeWriteConfigAs(configFile); err != nil {
// if error thrown because file exists, fine to ignore
if _, ok := err.(viper.ConfigFileAlreadyExistsError); !ok {
return config, err
}
}
if err := config.ReadInConfig(); err != nil {
fmt.Printf("read error %v\n", config)
return config, err
}
logging.Debug(logging.DStart, "CON Loaded configs from %#V", config.ConfigFileUsed())
// returning config object
return config, nil
}