Parsing YAML file in go

Hi,

Can anyone tell me how can I parse YAML file in vendor package folder in golang.

Thanks in advance!

There are multiple packages for parsing YAML files: https://godoc.org/?q=yaml

1 Like

yes @calmh but I want to read a yaml file which is under a vendor directory.Can you provide a sample to parse it?

It is no different parsing it there than anywhere else. I’m not exactly sure what you’re asking, sorry.

@calmh actully I am able to parse it at my local server but when I deployed it to heroku then it is throwing error -

open /app/vendor/github.com/ua-parser/uap-go/uap-core/regexes.yaml: no such file or directory

Please suggest!

So, the vendor directory is part of the source. When you are deploying, you are presumably deploying a binary and maybe not including this file. If it’s something that needs to be deployed together with the binary, you probably need to explicitly deploy this file as well, and use the path to that deployed file when parsing it.

1 Like

Another option is to embed the file into your binary using one of the many static file/bindata utilities. These are tools that take files and generate source code that include the contents of those files.

A third option is to generate the parsed form of the YAML as Go source code. This can be done by writing a small program something like:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"gopkg.in/yaml.v2"
)

func main() {
	log.SetFlags(log.Lshortfile)

	data, err := ioutil.ReadFile("regexes.yaml")
	if err != nil {
		log.Fatalln(err)
	}

	var v interface{}
	err = yaml.Unmarshal(data, &v)
	if err != nil {
		log.Fatalln(err)
	}

	f, err := os.Create("regexes.yaml.go")
	if err != nil {
		log.Fatalln(err)
	}
	defer func() {
		err := f.Close()
		if err != nil {
			log.Fatalln(err)
		}
	}()

	fmt.Fprintf(f, "package main\n\n")
	fmt.Fprintf(f, "var regexes = %#v\n", v)
}

As this was just a quick example, I did not unmarshal to more a more useful data type (which you probably already have) or format the generated code correctly.

1 Like

thanks @nathankerr ! It will surely help me.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.