Skip to content

Commit

Permalink
Add support for init with custom config file (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
wanliqun authored May 23, 2024
1 parent 21e06d0 commit ee471be
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
18 changes: 12 additions & 6 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ import (
// Parameters:
// - viperEnvPrefix : The prefix used for environment variables that `Viper` should consider
// while initializing configurations.
// - configPath : The path to the configuration file. If not provided, search for the default
// config file under current directory or `config` subfolder.
//
// Panics:
// - If any part of the initialization fails, this function will panic, causing the application
// to terminate abruptly.
func MustInit(viperEnvPrefix string) {
func MustInit(viperEnvPrefix string, configPath ...string) {
// Delegates to the shared initialization logic with no context for graceful shutdown.
mustInit(viperEnvPrefix, nil, nil)
mustInit(viperEnvPrefix, nil, nil, configPath...)
}

// MustInitWithCtx carries out the same initializations as `MustInit` except for support for
Expand All @@ -38,8 +40,11 @@ func MustInit(viperEnvPrefix string) {
// - wg: The wait group to track goroutines for shutdown synchronization.
// - viperEnvPrefix : The prefix used for environment variables that `Viper` should consider
// while initializing configurations.
func MustInitWithCtx(ctx context.Context, wg *sync.WaitGroup, viperEnvPrefix string) {
mustInit(viperEnvPrefix, ctx, wg)
// - configPath : The path to the configuration file. If not provided, search for the default
// config file under current directory or `config` subfolder.
func MustInitWithCtx(
ctx context.Context, wg *sync.WaitGroup, viperEnvPrefix string, configPath ...string) {
mustInit(viperEnvPrefix, ctx, wg, configPath...)
}

// mustInit is the internal function responsible for the core initialization steps.
Expand All @@ -48,10 +53,11 @@ func MustInitWithCtx(ctx context.Context, wg *sync.WaitGroup, viperEnvPrefix str
//
// Important: The order in which initializations are performed is critical due to
// dependencies between components.
func mustInit(viperEnvPrefix string, ctx context.Context, wg *sync.WaitGroup) {
func mustInit(
viperEnvPrefix string, ctx context.Context, wg *sync.WaitGroup, configPath ...string) {
// Initialize `Viper` to read configurations from a file or environment variables.
// The provided prefix is used to match and bind environment variables to config keys.
viper.MustInit(viperEnvPrefix)
viper.MustInit(viperEnvPrefix, configPath...)

// Initialize metrics collection based on the configurations loaded into `Viper`.
// Metrics are typically used for monitoring application performance.
Expand Down
24 changes: 16 additions & 8 deletions viper/viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
"github.com/spf13/viper"
)

var envKeyPrefix string // environment variable prefix
var (
envKeyPrefix string // environment variable prefix
)

func initEnv(envPrefix string) {
envKeyPrefix = strings.ToUpper(envPrefix + "_")
Expand All @@ -22,17 +24,23 @@ func initEnv(envPrefix string) {
// MustInit inits viper with provided env var prefix.
//
// Note that it will panic and exit if any error happens.
func MustInit(envPrefix string) {
func MustInit(envPrefix string, configPath ...string) {
logger := logrus.WithField("envPrefix", envPrefix)
initEnv(envPrefix)

// Read config file from current directory or under config folder.
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.AddConfigPath("./config")
if len(configPath) > 0 {
logger = logger.WithField("customConfig", configPath[0])
viper.SetConfigFile(configPath[0])
} else {
// Read config file from current directory or under config folder.
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.AddConfigPath("./config")
}

if err := viper.ReadInConfig(); err != nil {
logrus.WithError(err).Fatal("Failed to read config to initialize viper")
logger.WithError(err).Fatal("Failed to read config to initialize viper")
}

logrus.Info("Viper initialized")
logger.Info("Viper initialized")
}

0 comments on commit ee471be

Please sign in to comment.