go - 如何将 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 并将其写入文件。
解决方案
没有单个函数可以编码和写入文件,因此您需要:
- 使用创建文件
os.Create()
- 使用将结构编码到文件中
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)
}
推荐阅读
- postgresql - 如何在 Ansible 中使用美元引号创建 SQL 视图?
- java - MapView 不再显示
- python - python如何在指定的图像上绘图?
- python - 了解 findall() 正则表达式结果
- react-native - 带有 rsa-sha256 的 react-native 数字签名
- javascript - 如何使用按钮管理 CSS 轮播?
- macos - 切换暗模式时 NSAppearance 不更新
- javascript - 为什么纱线无法加载
- c - 与共享对象链接时未定义的引用
- javascript - 如何在 Node.js 中的路由参数之后期待一个特定的单词?