Reputation: 11
My configs contain multiple structured configs of an inner struct, in this case- a company.
At the top-level, I want access directly to a particular attribute in a company I know exists in my config.yaml.
Is it possible to have this unmarshalling using just struct tags?
package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
type Org struct {
Ceo string `yaml:"ceo"`
}
type Config struct {
Companies map[string]Org `yaml:"companies"`
GoogleCEO string `yaml:"companies.google.ceo"`
}
func main() {
var config Config
yamlFile := []byte(`companies:
google:
ceo: "Sundar Pichai"
amazon:
ceo: "Jeff Bezos"`)
err := yaml.Unmarshal(yamlFile, &config)
check(err)
fmt.Printf("config:\n%#v", config)
}
func check(e error) {
if e != nil {
panic(e)
}
}
https://go.dev/play/p/G_1NV46yWrv
Upvotes: 1
Views: 301
Reputation: 6018
Unfortunately, you cannot do it with tags.
Closest option is nested structs:
type Config struct {
Companies struct {
Google struct {
CEO string `yaml:"ceo"`
} `yaml:"google"`
} `yaml:"companies"`
}
https://go.dev/play/p/28pcPUiZvO-
Upvotes: 1