Skip to content

Commit

Permalink
fix: improve env variable substitution logic, only replace variables …
Browse files Browse the repository at this point in the history
…wrapped in curly braces (${var}) (#894)
  • Loading branch information
EquentR authored Dec 2, 2024
1 parent d621053 commit 3f253b3
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"bytes"
"fmt"
"os"
"regexp"
"strings"

"RedisShake/internal/log"

"github.com/a8m/envsubst"
"github.com/mcuadros/go-defaults"
"github.com/rs/zerolog"
"github.com/spf13/viper"
Expand Down Expand Up @@ -101,13 +101,14 @@ func LoadConfig() *viper.Viper {
if len(os.Args) == 2 {
logger.Info().Msgf("load config from file: %s", os.Args[1])
configFile := os.Args[1]
buf, err := envsubst.ReadFile(configFile)
file, err := os.ReadFile(configFile)
if err != nil {
logger.Error().Msgf("failed to read config file: %v", err)
os.Exit(1)
}
fallback := envWithFallback(string(file))
v.SetConfigType("toml")
err = v.ReadConfig(bytes.NewReader(buf))
err = v.ReadConfig(bytes.NewReader([]byte(fallback)))
if err != nil {
logger.Error().Msgf("failed to read config file: %v", err)
os.Exit(1)
Expand All @@ -124,3 +125,19 @@ func LoadConfig() *viper.Viper {
}
return v
}

// Custom substitution function that returns as is if the environment variable is empty
func envWithFallback(input string) string {
re := regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*?)}`)
return re.ReplaceAllStringFunc(input, func(match string) string {
varName := match[1:]
if strings.HasPrefix(varName, "{") && strings.HasSuffix(varName, "}") {
varName = varName[1 : len(varName)-1] // Remove { and }
}
value := os.Getenv(varName)
if value == "" {
return match // if the environment variable is empty return as is
}
return value
})
}

0 comments on commit 3f253b3

Please sign in to comment.