Go 如何以父子顺序构造yaml文件?
我想通过yaml文件使用golang来形成一个结构,但我发现很难做到这一点Go 如何以父子顺序构造yaml文件?,go,struct,yaml,Go,Struct,Yaml,我想通过yaml文件使用golang来形成一个结构,但我发现很难做到这一点 api: local: host: localhost port: 8085 develop: host: port: production: host: port: rest-api: local: host: localhost port: 8085 develop: host: port: production:
api:
local:
host: localhost
port: 8085
develop:
host:
port:
production:
host:
port:
rest-api:
local:
host: localhost
port: 8085
develop:
host:
port:
production:
host:
port:
这是我的yaml文件中的格式
预期的代码是我想创建一个本地、开发和生产格式的动态api url,如api:local=host+port,与开发和生产相同,可以轻松地动态配置和设置它
非常感谢您在golang struct中的帮助以及您的帮助。此在线资源将帮助您完成以下任务: 粘贴yaml会产生以下结果:
type AutoGenerated struct {
API struct {
Local struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"local"`
Develop struct {
Host interface{} `yaml:"host"`
Port interface{} `yaml:"port"`
} `yaml:"develop"`
Production struct {
Host interface{} `yaml:"host"`
Port interface{} `yaml:"port"`
} `yaml:"production"`
} `yaml:"api"`
RestAPI struct {
Local struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"local"`
Develop struct {
Host interface{} `yaml:"host"`
Port interface{} `yaml:"port"`
} `yaml:"develop"`
Production struct {
Host interface{} `yaml:"host"`
Port interface{} `yaml:"port"`
} `yaml:"production"`
} `yaml:"rest-api"`
}
有明显的子类型重复。所以它可以被修剪
第一遍:
type Address struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type MyConfig struct {
API struct {
Local Address `yaml:"local"`
Develop Address `yaml:"develop"`
Production Address `yaml:"production"`
} `yaml:"api"`
RestAPI struct {
Local Address `yaml:"local"`
Develop Address `yaml:"develop"`
Production Address `yaml:"production"`
} `yaml:"rest-api"`
}
type Address struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type Deployment struct {
Local Address `yaml:"local"`
Develop Address `yaml:"develop"`
Production Address `yaml:"production"`
}
type MyConfig struct {
API Deployment `yaml:"api"`
RestAPI Deployment `yaml:"rest-api"`
}
第二次(和最后一次)通过:
type Address struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type MyConfig struct {
API struct {
Local Address `yaml:"local"`
Develop Address `yaml:"develop"`
Production Address `yaml:"production"`
} `yaml:"api"`
RestAPI struct {
Local Address `yaml:"local"`
Develop Address `yaml:"develop"`
Production Address `yaml:"production"`
} `yaml:"rest-api"`
}
type Address struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type Deployment struct {
Local Address `yaml:"local"`
Develop Address `yaml:"develop"`
Production Address `yaml:"production"`
}
type MyConfig struct {
API Deployment `yaml:"api"`
RestAPI Deployment `yaml:"rest-api"`
}