Home >Backend Development >Golang >How do I Parse YAML Files in Go?
Parsing YAML files in Go requires understanding the structure of the data and the appropriate data types to represent it.
Consider the following YAML file with firewall network rules:
--- firewall_network_rules: rule1: src: blablabla-host dst: blabla-hostname ...
To parse this file, we'll define a Config struct to represent the YAML contents:
type Config struct { Firewall_network_rules map[string][]string }
We'll then use the yaml package to unmarshal the YAML file into the Config struct:
func main() { filename, _ := filepath.Abs("./fruits.yml") yamlFile, err := ioutil.ReadFile(filename) if err != nil { panic(err) } var config Config err = yaml.Unmarshal(yamlFile, &config) if err != nil { panic(err) } fmt.Printf("Value: %#v\n", config.Firewall_network_rules) }
This approach works because the YAML file uses a nested map structure that corresponds to the Config struct.
To parse a more complex YAML file like a Kubernetes service manifest, we'll create a more complex struct:
type Service struct { APIVersion string `yaml:"apiVersion"` Kind string `yaml:"kind"` Metadata struct { Name string `yaml:"name"` Namespace string `yaml:"namespace"` Labels struct { RouterDeisIoRoutable string `yaml:"router.deis.io/routable"` } `yaml:"labels"` Annotations struct { RouterDeisIoDomains string `yaml:"router.deis.io/domains"` } `yaml:"annotations"` } `yaml:"metadata"` Spec struct { Type string `yaml:"type"` Selector struct { App string `yaml:"app"` } `yaml:"selector"` Ports []struct { Name string `yaml:"name"` Port int `yaml:"port"` TargetPort int `yaml:"targetPort"` NodePort int `yaml:"nodePort,omitempty"` } `yaml:"ports"` } `yaml:"spec"` }
We'll then unmarshal the YAML file into this struct:
var service Service err = yaml.Unmarshal(yourFile, &service) if err != nil { panic(err) } fmt.Print(service.Metadata.Name)
By using appropriate structs that match the YAML structure, we can effectively parse and represent complex YAML data in Go.
The above is the detailed content of How do I Parse YAML Files in Go?. For more information, please follow other related articles on the PHP Chinese website!