Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve env variable substitution logic, only replace variables wrapped in curly braces (${var}) #894

Merged
merged 1 commit into from
Dec 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
})
}