curusarn
curusarn

Reputation: 403

How to encode golang struct as TOML and write to a file using BurntSushi/toml library?

It is very simple to read and decode a TOML file using BurntSushi/toml library:

var config Config // struct that matches the structure of the TOML file
if _, err := toml.DecodeFile("path/to/file.toml", &config); err != nil {
    // failed to read and decode the file
    fmt.Fatal(err)
}
// at this point config struct contains the values from the file

I want to do the reverse: take a struct, encode it as TOML and write it to file.

Upvotes: 1

Views: 3632

Answers (1)

curusarn
curusarn

Reputation: 403

There is no single function to encode and write to file so you will need to:

  1. Create a file using os.Create()
  2. Encode the struct to the file using toml.Encoder.Encode()

Let's assume that we have a struct config that we want to write to file in TOML format:


f, err := os.Create("path/to/file.toml")
if err != nil {
    // failed to create/open the file
    log.Fatal(err)
}
if err := toml.NewEncoder(f).Encode(config); err != nil {
    // failed to encode
    log.Fatal(err)
}
if err := f.Close(); err != nil {
    // failed to close the file
    log.Fatal(err)

}

Upvotes: 2

Related Questions