Use the github.com/pelletier/go-toml/v2 library to parse TOML files into Go structs or write Go structs to TOML format.
package main
import (
"fmt"
"os"
"github.com/pelletier/go-toml/v2"
)
type Config struct {
Name string `toml:"name"`
Version int `toml:"version"`
}
func main() {
// Read
var cfg Config
if err := toml.UnmarshalFile("config.toml", &cfg); err != nil {
fmt.Println(err)
return
}
// Write
cfg.Name = "MyApp"
cfg.Version = 2
if err := toml.MarshalFile(cfg, "output.toml"); err != nil {
fmt.Println(err)
return
}
}
Install the library first:
go get github.com/pelletier/go-toml/v2