Skip to content

Commit

Permalink
fix(expand env): change os.ExpandEnv to regex (#1231)
Browse files Browse the repository at this point in the history
* fix(expand env): change os.ExpandEnv to regex

* fix: MustCompile

* fix: regex
  • Loading branch information
Akegarasu authored Dec 9, 2021
1 parent 0211a0e commit 49aedc9
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion modules/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
_ "embed" // embed the default config file
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
}

0 comments on commit 49aedc9

Please sign in to comment.