首页 > 解决方案 > 如何将 golang 结构编码为 TOML 并使用 BurntSushi/toml 库写入文件?

问题描述

使用 BurntSushi/toml 库读取和解码 TOML 文件非常简单:

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

我想做相反的事情:获取一个结构,将其编码为 TOML 并将其写入文件。

标签: gotoml

解决方案


没有单个函数可以编码和写入文件,因此您需要:

  1. 使用创建文件os.Create()
  2. 使用将结构编码到文件中toml.Encoder.Encode()

假设我们有一个config想要以 TOML 格式写入文件的结构:


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)

}

推荐阅读