1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00

docs: document default env placeholder

This commit is contained in:
wdvxdr 2022-02-09 15:01:38 +08:00
parent 8eefcc8cc8
commit e1937e9f15
No known key found for this signature in database
GPG Key ID: 703F8C071DE7A1B6
3 changed files with 19 additions and 6 deletions

View File

@ -174,7 +174,7 @@ go-cqhttp 配置文件可以使用占位符来读取**环境变量**的值。
```yaml
account: # 账号相关
uin: ${CQ_UIN} # 读取环境变量 CQ_UIN
password: ${CQ_PASSWORD} # 读取环境变量 CQ_UIN
password: ${CQ_PWD:123456} # 当 CQ_PWD 为空时使用默认值 123456
```
## 在线状态

View File

@ -152,14 +152,14 @@ func generateConfig() {
// 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_:]*)}`)
r := regexp.MustCompile(`\${([a-zA-Z_]+[a-zA-Z0-9_:/.]*)}`)
return r.ReplaceAllStringFunc(s, func(s string) string {
s = strings.Trim(s, "${}")
// todo: use strings.Cut once go1.18 is released
placeholder, default_, ok := cut(s, ":")
m := mapping(placeholder)
before, after, ok := cut(s, ":")
m := mapping(before)
if ok && m == "" {
return default_
return after
}
return m
})

View File

@ -6,6 +6,9 @@ import (
)
func Test_expand(t *testing.T) {
nullStringMapping := func(_ string) string {
return ""
}
tests := []struct {
src string
mapping func(string) string
@ -23,9 +26,19 @@ func Test_expand(t *testing.T) {
},
{
src: "foo: ${bar:123456}",
mapping: func(s string) string { return "" },
mapping: nullStringMapping,
expected: "foo: 123456",
},
{
src: "foo: ${bar:127.0.0.1:5700}",
mapping: nullStringMapping,
expected: "foo: 127.0.0.1:5700",
},
{
src: "foo: ${bar:ws//localhost:9999/ws}",
mapping: nullStringMapping,
expected: "foo: ws//localhost:9999/ws",
},
}
for i, tt := range tests {
if got := expand(tt.src, tt.mapping); got != tt.expected {