mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-05-04 19:17:37 +08:00
fix(expand env): change os.ExpandEnv to regex (#1231)
* fix(expand env): change os.ExpandEnv to regex * fix: MustCompile * fix: regex
This commit is contained in:
parent
0211a0ea96
commit
49aedc99fe
@ -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
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user