Reputation: 13500
I have the following struct YAML:
type YamlConfig struct {
Items struct {
RiskyRoles []struct {
Name string `yaml:"name"`
Rules []struct{
Verbs []string `yaml:"verbs"`
ResourceOperator string `yaml:"resourcesOperator"`
Resources []string `yaml:"resources"`
}
} `yaml:"RiskyRoles"`
} `yaml:"Items"`
}
I have a function that parse a YAML file to an object and then I want to send the Rules
struct object to a function named DoingStuff(..)
:
yamlFile, err := ioutil.ReadFile("actionItems.yaml")
if err != nil {
fmt.Printf("Error reading YAML file: %s\n", err)
} else{
var yamlConfig YamlConfig
err = yaml.Unmarshal(yamlFile, &yamlConfig)
if err != nil {
fmt.Printf("Error parsing YAML file: %s\n", err)
}
for _, yamlRole := range yamlConfig.Items.RiskyRoles{
DoingStuff(yamlRole.Rules)
}
}
But inside the function DoingStuff
, the struct object Rules
is not recognized:
func DoingStuff(yamlRules []struct{}) {
// Not recognize ****
for _, rule := range yamlRules {
fmt.Print(rule.ResourceOperator)
}
}
How can I convert it to:
Rules []struct{
Verbs []string `yaml:"verbs"`
ResourceOperator string `yaml:"resourcesOperator"`
Resources []string `yaml:"resources"`
}
Should I re-declare this struct again? Or cast using interfaces ?
EDIT:
I added new struct and used it inside the YamlConfig
struct but the parse failed to parse the Rules:
type RulesStruct struct {
Rules []struct{
Verbs []string `yaml:"verbs"`
ResourceOperator string `yaml:"resourcesOperator"`
Resources []string `yaml:"resources"`
}
}
type YamlConfig struct {
Items struct {
RiskyRoles []struct {
Name string `yaml:"name"`
Message string `yaml:"message"`
Priority string `yaml:"priority"`
Rules []RulesStruct
} `yaml:"RiskyRoles"`
} `yaml:"Items"`
}
Upvotes: 0
Views: 244
Reputation: 13500
Thanks to @mkporiva help, I changed the structs like that:
type RulesStruct struct {
Verbs []string `yaml:"verbs"`
ResourceOperator string `yaml:"resourcesOperator"`
Resources []string `yaml:"resources"`
}
type YamlConfig struct {
Items struct {
RiskyRoles []struct {
Name string `yaml:"name"`
Message string `yaml:"message"`
Priority string `yaml:"priority"`
Rules []RulesStruct
} `yaml:"RiskyRoles"`
} `yaml:"Items"`
}
Now it works fine.
Upvotes: 1