Skip to content

Instantly share code, notes, and snippets.

@FilBot3
Last active July 7, 2016 03:07
Show Gist options
  • Select an option

  • Save FilBot3/c3c6a18d203d544dd4f67fe6fc9cf8fd to your computer and use it in GitHub Desktop.

Select an option

Save FilBot3/c3c6a18d203d544dd4f67fe6fc9cf8fd to your computer and use it in GitHub Desktop.
GO go-yaml read, parse, and write. The indentations are a bit off on the write.
/**
*
*
*/
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
type Config struct {
Foo string `yaml:"foo"`
Baz string `yaml:"baz"`
Fart []string `yaml:"fart"`
Data `yaml:"data"`
}
type Data struct {
Item string `yaml:"item"`
}
func checkerr(err error) {
if err != nil {
panic(err)
}
}
func main() {
// Take the first command line argument which is the
// name of the YAML file
filename := os.Args[1]
// Create an instance of the Config struct
var config Config
// Read the YAML file, and check for errors.
source, err := ioutil.ReadFile(filename)
checkerr(err)
// Parse, or Unmarshal the YAML file into the
// config Struct instance.
err = yaml.Unmarshal(source, &config)
checkerr(err)
fmt.Println(config)
fmt.Println(config.Baz)
fmt.Println(config.Fart)
fmt.Println(config.Fart[0])
// Take the Struct Data, and store the byte data
// to the variable. Then check for errors.
marshalled_data, err := yaml.Marshal(&config)
checkerr(err)
fmt.Println("---\n", string(marshalled_data))
// Create a file named ""
file, err := os.Create("output.txt")
checkerr(err)
// Close the file pointer.
defer file.Close()
// Write the Marshalled data to the file
stuff, err := file.Write(marshalled_data)
checkerr(err)
// For some reason, I still have to write this.
// The variable is the number of bytes written to
// the file.
fmt.Println(stuff)
}
---
# This should still work with comments in the code.
foo: "Bar"
# Whatever you pick for a library, should work.
baz: "Buns"
fart:
- uno
- dos
data:
item: "farts"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment