我有以下yaml:
segmentforward: ""
segmentbackward: ""
listforward: ""
promptready: "➜"
enabledhooks: ["alert"]
enabledsegments: ["host", "path", "python_env", "aws", "git", "filler", "command", "timestamp", "newline", "prompt_ready"]
hostsegment: { fgcolor: 250, bgcolor: 238 }
pathsegment: { fgcolor: 15, bgcolor: 31 }
pythonenvsegment: { fgcolor: 15, bgcolor: 22 }
awssegment: { fgcolor: 172, bgcolor: 238 }
gitsegment: { fgcolor: 238, bgcolor: 148 }
fillersegment: { fgcolor: 251, bgcolor: 251 }
commandsegment: { fgcolor: 238, bgcolor: 250 }
timestampsegment: { fgcolor: 250, bgcolor: 238 }
promptreadysegment: { fgcolor: 238, bgcolor: 251 }
我试图使用以下代码解析此yaml:
package config
import (
"gopkg.in/yaml.v2"
"io/ioutil"
)
type Config struct {
SegmentForward string
SegmentBackward string
ListForward string
PromptReady string
EnabledHooks []string
EnabledSegments []string
HostSegment struct {
FgColor int
BgColor int
}
}
func LoadConfig(path string) (config Config) {
data, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
err = yaml.Unmarshal(data, &config)
if err != nil {
panic(err)
}
return config
}
但这给了我错误:
panic: yaml: unmarshal errors:
line 18: cannot unmarshal !!map into string
goroutine 1 [running]:
panic(0x3364c0, 0xc42014a9c0)
/usr/local/Cellar/go/1.7.4/libexec/src/runtime/panic.go:500 +0x1a1
github.com/brujoand/sbp/config.LoadConfig(0x3b7138, 0x23, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
/opt/go/src/github.com/brujoand/sbp/config/config.go:30 +0x12d
main.main()
/opt/go/src/github.com/brujoand/sbp/main.go:18 +0x50
我想要的是能够直接引用这些片段而无需查找地图。然后在每个细分中都有相同类型的字段。我知道我在Yaml中的命名并不好(抱歉),但是现在我试图理解如何以简单的方式访问这些字段。
答案 0 :(得分:0)
这个yaml可以完美地解组(因为你不想使用地图):
type Config struct {
SegmentForward string
SegmentBackward string
ListForward string
PromptReady string
EnabledHooks []string
EnabledSegments []string
HostSegment, PathSegment, PythonEnvSegment, AWSSegment, GitSegment segment
FillerSegment, CommandSegment, TimestampSegment, PromptReadySegment segment
}
type segment struct {
FgColor int
BgColor int
}