diff --git a/modules/config/config.go b/modules/config/config.go index 33930cc..4dee915 100644 --- a/modules/config/config.go +++ b/modules/config/config.go @@ -6,6 +6,7 @@ import ( _ "embed" // embed the default config file "fmt" "os" + "regexp" "strconv" "strings" "sync" @@ -96,7 +97,7 @@ func Parse(path string) *Config { file, err := os.ReadFile(path) config := &Config{} if err == nil { - err = yaml.NewDecoder(strings.NewReader(os.ExpandEnv(string(file)))).Decode(config) + err = yaml.NewDecoder(strings.NewReader(expand(string(file), os.Getenv))).Decode(config) if err != nil && !fromEnv { log.Fatal("配置文件不合法!", err) } @@ -182,3 +183,17 @@ func generateConfig() { fmt.Println("默认配置文件已生成,请修改 config.yml 后重新启动!") _, _ = input.ReadString('\n') } + +// expand 使用正则进行环境变量展开 +// os.ExpandEnv 字符 $ 无法逃逸 +// https://github.com/golang/go/issues/43482 +func expand(s string, mapping func(string) string) string { + r := regexp.MustCompile(`\${([a-zA-Z_]+[a-zA-Z0-9_]*)}`) + re := r.FindAllStringSubmatch(s, -1) + for _, i := range re { + if len(i) == 2 { + s = strings.ReplaceAll(s, i[0], mapping(i[1])) + } + } + return s +}