configloader
configloader is a go library for loading configuration from multiple sources.
pkg/config
The github.com/pastdev/pkg/config package provides the core configuration loading library.
The library itself is very simple in that it has a single interface (SourceLoader) that can be implemented for any type of source.
These source loader instances are aggregated together in a Sources object that can then be used to load and merge multiple sources together.
Subsequent sources will merge their values over the top of any existing values so the latest defined wins.
sources := config.Sources[AppConfig]{
config.FileSource[AppConfig]{Path: "~/.config/app.yml"},
config.DirSource[AppConfig]{Path: "~/.config/app.d"},
}
sources.Load(&cfg)
See the example or tests for more use cases.
pkg/config Logger
This library uses zerolog for logging.
The Logger can be set by consumers as follows:
import(
"github.com/pastdev/configloader/pkg/config"
)
...
config.Logger = zerolog.New(os.Stderr).Level(zerolog.TraceLevel).With().Timestamp().Logger()
pkg/cobra
The github.com/pastdev/pkg/cobra package provides CLI integration with cobra.
There are 2 mandatory, and 2 optional integration points.
First you need to define your Config object:
cfg := cobraconfig.Config[map[any]any]{
DefaultSources: config.Sources[map[any]any]{
config.FileSource[map[any]any]{Path: "/etc/configloader.yml"},
config.DirSource[map[any]any]{Path: "/etc/configloader.d"},
config.FileSource[map[any]any]{Path: "~/.config/configloader.yml"},
config.DirSource[map[any]any]{Path: "~/.config/configloader.d"},
},
}
Then you need to Load() the configuration object in a the PersistentPreRunE function of your root command:
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
err := cfg.Load()
if err != nil {
return fmt.Errorf("load config: %w", err)
}
return nil
},
Optionally, you can use flags to allow your user to replace the DefaultSources:
cfg.PersistentFlags(&root).FileSourceVar(
config.YamlUnmarshal,
"config",
"location of one or more config files")
cfg.PersistentFlags(&root).DirSourceVar(
config.YamlUnmarshal,
"config-dir",
"location of one or more config directories")
And add a config subcommand to your root command for printing out the configuration:
cfg.AddSubCommandTo(&root)