【问题标题】:How to encode golang struct as TOML and write to a file using BurntSushi/toml library?如何将 golang 结构编码为 TOML 并使用 BurntSushi/toml 库写入文件?
【发布时间】:2020-10-19 11:23:39
【问题描述】:

使用 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 并将其写入文件。

【问题讨论】:

    标签: go toml


    【解决方案1】:

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

    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)
    
    }
    

    【讨论】:

    • 检查f.Close()的返回值,确保文件写入成功。
    • @TimCooper 我已经更新了关闭文件时检查错误的答案。
    猜你喜欢
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多