好的,所以我没有看到的模式非常明显:配置的“最深叶”覆盖了下面的所有内容,无论是使用给定的数据还是使用空值的 go 默认值:
这意味着像这样的结构......
[key_string]:
input:
listener: [string]
static: [string]
output:
listener: [string]
details:
filter: [string]
retention: [string]
...默认使用数据...
defaults:
input:
listener: 127.0.0.1:8910
static: default
output:
listener: 127.0.0.1:8989
details:
filter: '*foo*'
retention: 3h
...用这种形式的 yaml 喂食..
empty:
both:
input:
output:
input: &input
input:
input-modified-with-anchor:
<<: *input
input:
static: NOTDEFAULT
input-modified-without-anchor:
input:
static: NOTDEFAULT
output: &output
output:
output-modified-with-anchor:
<<: *output
output:
details:
filter: NOTDEFAULT
output-modified-without-anchor:
output:
details:
filter: NOTDEFAULT
...原来是...
both:
input:
listener: ""
static: ""
output:
listener: ""
details:
filter: ""
retention: ""
empty:
input:
listener: ""
static: ""
output:
listener: ""
details:
filter: ""
retention: ""
input:
input:
listener: ""
static: ""
output:
listener: 127.0.0.1:8989
details:
filter: '*foo*'
retention: 3h
input-modified-with-anchor:
input:
listener: 127.0.0.1:8910
static: NOTDEFAULT
output:
listener: 127.0.0.1:8989
details:
filter: '*foo*'
retention: 3h
input-modified-without-anchor:
input:
listener: 127.0.0.1:8910
static: NOTDEFAULT
output:
listener: 127.0.0.1:8989
details:
filter: '*foo*'
retention: 3h
对于我的用例,这是一个过于复杂的行为,因此我尝试了一种不同的方法:如果需要,我将默认配置注入 yaml 并在每个部分中引用其锚点。我觉得这对最终用户来说更加透明和可重复。这是一个丑陋的函数草稿:
func injectYAML(data []byte) ([]byte, error) {
// render a default section an add an anchor
key := "injected_defaults"
defaultData := Config{key: Defaults()}
var defaultSection []byte
defaultSection, _ = yaml.Marshal(defaultData)
defaultSection = bytes.Replace(defaultSection, []byte(key+":"), []byte(key+": &"+key), 1)
// get list of sections in input data
c := Config{}
err := yaml.Unmarshal(data, &c)
if err != nil {
return data, fmt.Errorf("Error while reading sections from yaml: %s", err.Error())
}
// remove "---" at beginning when present
data = bytes.TrimLeft(data, "---")
// add reference to default section to each section
lines := bytes.Split(data, []byte("\n"))
var updatedLines [][]byte
for _, line := range lines {
updatedLines = append(updatedLines, line)
for section := range c {
if bytes.HasPrefix(line, []byte(section+":")) {
updatedLines = append(updatedLines, []byte(" <<: *"+key))
}
}
}
updatedData := bytes.Join(updatedLines, []byte("\n"))
// compose injected yaml
out := []byte("---\n")
out = append(out, defaultSection...)
out = append(out, updatedData...)
return out, nil
}
完整示例位于:https://github.com/unprofession-al/configuration/tree/7c2eb7da58b51f52b50f2a0fbac193c799c9eb08