Watching Configuration Files

Let's watch our configuration files for changes.

Watching configuration files is a very exciting feature that opens the door for a dynamic configuration where you can control the behavior of your program without re-running it. We will also demonstrate how Viper supports multiple configuration files.

Watching configuration files for changes

So far, we have read the configuration once, but some programs run for a long time and need to respond to changes in configuration. You can periodically re-read the config file to detect when it changed, but Viper can also do that for you. The following program watches the config.toml, file calling viper.WatchConfig() and then the viper.OnConfigChange() function and passing a function that reads the configuration again:

Once the program has run and displayed the values of a and b, click on “+” to open another terminal, the type nano /usercode/config.toml, and modify the values of the variables. Switch back to the other terminal tab, and you will see that the program has displayed the updated values.

Get hands-on with 1400+ tech skills courses.