How do I encode a struct to/from TOML in Go?

In Go, you can easily work with TOML files by using the github.com/BurntSushi/toml library. This library allows encoding and decoding of structs to TOML format.

Example Code

import ( "encoding/json" "fmt" "log" "github.com/BurntSushi/toml" ) // Config is a struct that represents the configuration structure type Config struct { Title string `toml:"title"` Owner Owner `toml:"owner"` } // Owner is a nested struct for owner details type Owner struct { Name string `toml:"name"` DOB string `toml:"dob"` } // Encode a struct to TOML func encodeToml(cfg Config) (string, error) { var buf []byte if err := toml.NewEncoder(&buf).Encode(cfg); err != nil { return "", err } return string(buf), nil } // Decode TOML to a struct func decodeToml(data string) (Config, error) { var cfg Config if _, err := toml.Decode(data, &cfg); err != nil { return cfg, err } return cfg, nil } func main() { cfg := Config{ Title: "TOML Example", Owner: Owner{ Name: "John Doe", DOB: "1985-01-01", }, } // Encode to TOML tomlData, err := encodeToml(cfg) if err != nil { log.Fatal(err) } fmt.Println(tomlData) // Decode from TOML var newCfg Config newCfg, err = decodeToml(tomlData) if err != nil { log.Fatal(err) } fmt.Printf("Decoded Config: %+v\n", newCfg) }

Go TOML encoding decoding configuration BurntSushi