我想通过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:
host:
port:
这是我的Yaml文件中的格式
这是我想要的代码,我想以本地,开发和生产格式创建一个动态api url,例如api:local = host + port,要进行开发和生产,以轻松地对其进行动态配置和设置
非常感谢您在golang结构中的帮助,也为您提供帮助。
答案 0 :(得分:1)
此在线资源将使您半途而废:
https://mengzhuo.github.io/yaml-to-go/
粘贴您的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"`
}