如何在Golang中解码和编码.toml文件的特定部分?

发布于 2025-01-29 19:53:01 字数 431 浏览 7 评论 0原文

我有点新手Burntsushi/Toml,想了解以下案件的解决方案。

假设我们有一个示例。toml文件,

[foo]
fighter = "this-is-a-call"
gu = "fish-with-wrong-spelling"

[bar]
beer = "guinness"
snacks = "pickled-eggs"

[more_examples_below]
...

据我正确理解,toml.decodefile(path,struct)用于读取整个示例。

不过,我不明白我应该如何仅针对[bar]零件进行解码/编码?

因此,我应该在Golang映射所有config.toml中定义整个结构吗?如果是,那么是否有另一种方法可以这样做,只是为1个特定块定义一个结构?

I'm kinda new to BurntSushi/toml and want to learn what are the solutions for the case below.

Let's say we have this example.toml file

[foo]
fighter = "this-is-a-call"
gu = "fish-with-wrong-spelling"

[bar]
beer = "guinness"
snacks = "pickled-eggs"

[more_examples_below]
...

As I understand correctly, toml.DecodeFile(path, struct) is used for reading the whole example.toml into golang code.

Still, I don't understand how should I do decoding/encoding only for the [bar] part?

Thus, should I define the whole struct in golang mapping all config.toml? If yes, then is there another way no to do so and just define a struct for 1 specific block?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙厌世 2025-02-05 19:53:01

如果您需要编辑现有.TOML文件的特定部分,则VIPER可以成为此工作中的有用替代方法。一些关于如何实现的想法草案

fh, err := os.OpenFile(path, os.O_RDWR, 0777)
if err != nil {
    return err
}

viper.SetConfigType("toml")
err = viper.ReadConfig(fh)
if err != nil {
    return err
}

viper.Set("bar", foo.String())
err = viper.WriteConfigAs(path)

if err != nil {
    return err
}

If you need to edit a specific part of an existing .toml file, viper can be a helpful alternative in this job. Some draft idea of how it can be achieved

fh, err := os.OpenFile(path, os.O_RDWR, 0777)
if err != nil {
    return err
}

viper.SetConfigType("toml")
err = viper.ReadConfig(fh)
if err != nil {
    return err
}

viper.Set("bar", foo.String())
err = viper.WriteConfigAs(path)

if err != nil {
    return err
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文