Skip to content

Commit

Permalink
chore: change config loading priority
Browse files Browse the repository at this point in the history
  • Loading branch information
greenhat616 committed Sep 14, 2023
1 parent af52c73 commit 3011ef1
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions prestart/init_config_driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,22 @@ package prestart

import (
"bytes"
"github.com/cockroachdb/errors"
"github.com/hitokoto-osc/Moe/config"
"github.com/hitokoto-osc/Moe/logging"
"github.com/spf13/viper"
"go.uber.org/zap"
"os"
"strings"

"github.com/hitokoto-osc/Moe/config"
"github.com/spf13/viper"
)

// The Config Parse Driver is served by viper
func initConfigDriver() {
logger := logging.GetLogger()
defer logger.Sync()
config.SetDefault()
// Parse env config
viper.SetEnvPrefix("moe") // like: MOE_PORT=8000
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

// Set default viper information
viper.SetConfigName("config")
viper.SetConfigType("toml") // Toml is the best!
if config.File != "" {
content, err := os.ReadFile(config.File)
if err != nil {
Expand Down Expand Up @@ -53,8 +47,20 @@ func initConfigDriver() {
viper.AddConfigPath("../config")
err := viper.ReadInConfig()
if err != nil {
logger.Fatal("[init] Fatal error while reading config file.", zap.Error(err))
var e viper.ConfigFileNotFoundError
if !errors.As(err, &e) {
logger.Fatal("[init] Fatal error while reading config file.", zap.Error(err))
}
logger.Warn("[init] No config file detected, reading config from env.")
}
}
// Parse env config
viper.SetEnvPrefix("moe") // like: MOE_PORT=8000
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
logger.Debug("[init] config is parsed.",
zap.String("config_file_used", viper.ConfigFileUsed()),
zap.Any("settings", viper.AllSettings()),
)
config.Inject()
}

0 comments on commit 3011ef1

Please sign in to comment.