How to decode and encode a specific part of .toml file in golang?

Viewed 169

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?

1 Answers

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