I'm attempting to read a YAML file using GO and mapping it to a structure that I've defined. The YAML is below:
--- # go_time_tracker.yml
owner: "Phillip Dudley"
initialized: "2012-10-31 15:50:13.793654 +0000 UTC"
time_data:
- action: "start"
time: "2012-10-31 15:50:13.793654 +0000 UTC"
- action: "stop"
time: "2012-10-31 16:00:00.000000 +0000 UTC"
I used the following code to read in the file, Unmarshal the data, and then print some of the data.
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"time"
)
type Date_File struct {
Owner string `yaml:"owner"`
Init time.Time `yaml:"initialized"`
TimeData []Time_Data `yaml:"time_data"`
}
type Time_Data struct {
//
Action string `yaml:"action"`
Time time.Time `yaml:"time"`
}
func checkerr(err error) {
if err != nil {
log.Fatal(err)
}
}
func read() (td *Date_File) {
//td := &Date_File{}
gtt_config, err := ioutil.ReadFile("go_time_tracker.yml")
checkerr(err)
err = yaml.Unmarshal(gtt_config, &td)
return td
}
func main() {
//
time_data := read()
fmt.Println(time_data)
fmt.Println(time_data.TimeData[0])
fmt.Println(time_data.Owner)
}
When I run this, the first fmt.Println(time_data)
works, showing the reference and its data. The next line though fails saying that the index is out of range. This is the error:
$ go run yaml_practice_2.go
&{Phillip Dudley 0001-01-01 00:00:00 +0000 UTC []}
panic: runtime error: index out of range
goroutine 1 [running]:
panic(0x559840, 0xc82000a0e0)
/usr/lib/go-1.6/src/runtime/panic.go:481 +0x3e6
main.main()
/home/predatorian/Documents/go/src/predatorian/yaml/yaml_practice_2.go:41 +0x2aa
exit status 2
I then thought maybe my YAML wasn't formatted properly, so I loaded the YAML file into Ruby's IRB, and this is what I got.
irb(main):004:0> data2 = YAML.load(File.read("go_time_tracker.yml"))
=> {"owner"=>"Phillip Dudley", "initialized"=>"2012-10-31 15:50:13.793654 +0000 UTC", "time_data"=>[{"action"=>"start", "time"=>"2012-10-31 15:50:13.793654 +0000 UTC"}, {"action"=>"stop", "time"=>"2012-10-31 16:00:00.000000 +0000 UTC"}]}
The IRB output shows that my YAML is formatted properly, however, I don't think I'm Unmarshalling it properly then. However, I'm not sure what I would need to do to get this to work. I'm sure I'm not thinking of how to do this properly since Ruby hides a lot of it.