Reputation: 1
I am trying to create a simple cli tool in Go using a TOML config file. I want to be able to store frequent commands I use on the command line for other tools, in a TOML file and use my CLI program to recall those. I want to make adding a new tool / command to the TOML file as easy as possible for other users. The trouble I am having is getting Go to recognize a new tool added to the TOML config file, without manually opening my config.go file and adding the tool to the config struct that is holding the parsed TOML data. Example TOML config:
# Configuration File
#
[assetfinder]
default = "assetfinder -subs-only {{TARGET}}"
silent = "assetfinder -subs-only {{TARGET}} --silent"
[subfinder]
default = "subfinder -u {{TARGET}}"
silent = "subfinder -u {{TARGET}} --silent"
I want a user to be able to add another tool/command without having to touch the source code and manually add it to the struct. Here is config.go:
package config
import (
"github.com/spf13/viper"
)
type Config struct {
Assetfinder map[string]string
Subfinder map[string]string
}
func Load() (*Config, error) {
v := viper.New()
v.SetConfigName("config")
v.AddConfigPath(".")
err := v.ReadInConfig()
if err != nil {
return nil, err
}
c := &Config{}
err = v.Unmarshal(c)
return c, err
}
Upvotes: 0
Views: 488
Reputation: 146
The viper has a solution about "Watching and re-reading config files". https://github.com/spf13/viper#watching-and-re-reading-config-files.
You just need to register to OnConfigChange
event and call WatchConfig
:
err := v.ReadInConfig()
if err != nil {
return nil, err
}
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
// TODO: read config from viper and update you logic
})
viper.WatchConfig()
The WatchConfig
implements is in https://github.com/spf13/viper/blob/master/viper.go#L431
fsnotify
to watch file changeReadInConfig
to updateonConfigChange
eventUpvotes: 0