forked from nixcn/nixcn-cms
Fix config module for unit test
Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
@@ -7,28 +7,35 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func Init() {
|
||||
// Set config path by env
|
||||
confPath := os.Getenv("CONFIG_PATH")
|
||||
if confPath == "" {
|
||||
confPath = "config.yaml"
|
||||
func ConfigDir() string {
|
||||
env := os.Getenv("CONFIG_PATH")
|
||||
if env != "" {
|
||||
return env
|
||||
}
|
||||
return "."
|
||||
}
|
||||
|
||||
func Init() {
|
||||
// Read global config
|
||||
viper.SetConfigFile(confPath)
|
||||
viper.SetDefault("Server", serverDef)
|
||||
viper.SetDefault("Database", databaseDef)
|
||||
viper.SetConfigName("config")
|
||||
viper.SetConfigType("yaml")
|
||||
viper.AddConfigPath(ConfigDir())
|
||||
|
||||
// Bind ENV
|
||||
viper.BindEnv("server.address", "SERVER_ADDRESS")
|
||||
viper.BindEnv("server.debug_mode", "SERVER_DEBUG_MODE")
|
||||
viper.BindEnv("server.file_logger", "SERVER_FILE_LOGGER")
|
||||
viper.BindEnv("server.jwt_secret", "SERVER_JWT_SECRET")
|
||||
viper.BindEnv("database.type", "DATABASE_TYPE")
|
||||
viper.BindEnv("database.host", "DATABASE_HOST")
|
||||
viper.BindEnv("database.name", "DATABASE_NAME")
|
||||
viper.BindEnv("database.username", "DATABASE_USERNAME")
|
||||
viper.BindEnv("database.password", "DATABASE_PASSWORD")
|
||||
|
||||
conf := &config{}
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
// Dont generate config when using dev mode
|
||||
if os.Getenv("GO_ENV") == "test" || os.Getenv("CONFIG_PATH") != "" {
|
||||
log.Fatalf("[Config] failed to read config %s: %v", confPath, err)
|
||||
}
|
||||
|
||||
log.Println("Can't read config, trying to modify!")
|
||||
if err := viper.WriteConfig(); err != nil {
|
||||
log.Fatal("[Config] Error writing config: ", err)
|
||||
}
|
||||
log.Fatalln("Can't read config!")
|
||||
}
|
||||
if err := viper.Unmarshal(conf); err != nil {
|
||||
log.Fatal(err)
|
||||
|
||||
Reference in New Issue
Block a user