Here is a list of YAML parsers for Go programming language. For each one, I will provide a short description, an evaluation and an example source code.
This parser is very handy to manage configuration files. You declare a struct that maps the structure of the YAML configuration file and you pass a reference to this struct to the parser while loading configuration file. This parser will populate struct with data in the file.
This parser is probably the best way to manage YAML configuration files.
This is a low level parser, which means that a file will result in a nodes tree that you will have to explore by hand (as in the example that follows):
package main
import (
"fmt"
"github.com/kylelemons/go-gypsy/yaml"
"os"
)
func nodeToMap(node yaml.Node) (yaml.Map) {
m, ok := node.(yaml.Map)
if !ok {
panic(fmt.Sprintf("%v is not of type map", node))
}
return m
}
func nodeToList(node yaml.Node) (yaml.List) {
m, ok := node.(yaml.List)
if !ok {
panic(fmt.Sprintf("%v is not of type list", node))
}
return m
}
func main() {
filename := os.Args[1]
file, err := yaml.ReadFile(filename)
if err != nil {
panic(err)
}
value := nodeToList(nodeToMap(file.Root)["bar"])[0]
fmt.Printf("Value: %#v\n", value)
}
To run this sample code, execute following command:
package main
import (
"fmt"
"github.com/beego/goyaml2"
"os"
)
func nodeToMap(node interface{}) map[string]interface{} {
m, ok := node.(map[string]interface{})
if !ok {
panic(fmt.Sprintf("%v is not of type map", node))
}
return m
}
func nodeToList(node interface{}) []interface{} {
m, ok := node.([]interface{})
if !ok {
panic(fmt.Sprintf("%v is not of type list", node))
}
return m
}
func main() {
filename := os.Args[1]
file, err := os.Open(filename)
if err != nil {
panic(err)
}
object, err := goyaml2.Read(file)
if err != nil {
panic(err)
}
value := nodeToList(nodeToMap(object)["bar"])[0]
fmt.Printf("Value: %#v\n", value)
}
This is a layer around GoYAML to simplify YAML file parsing. You don't have to describe document structure, you can directly access content exploring the tree. Nevertheless, what you save on one side (not writing the document structure), you loose on the other (writing code to explore the tree and managing errors)...