With External Loaders
tiny3 Example
In this section, we introduce how to enable auto-loading app settings from external souces (file) by using hedzr/cmdr-loaders.
The sample app is,
There is a sample settings file named as tiny3-app.toml within the root folder of hedzr/cmdr-tests repo. It contains:
The settings will be loaded in running tiny3 app. To ensure it, we could invoke tiny3 --full to display the whold data tree:
The notable point is the highlight line, which shows the value of app.tiny3.foo was loaded properly.
Searching the settings folders
hedzr/cmdr-loaders provides a file loader to compliant with GNU Folder Spec, UNIX Filesystem Conventions (wiki) and Filesystem Hierarchy Standard (wiki).
Therefore, cmdr and cmdr-loaders will auto-search the app-settings folders from:
- Primary:
/etc/<app-name> - Secondary:
$HOME/.config/<app-name> - Alternative(s):
.and<exeutable-dir>
to look for whether a <app-name>.toml file exists or not.
If it's found (such as tiny3-app.toml in this demo), load it into memory and merge the parsed settings into cmdr.App.
Then, for Primary or Secondary setting source, check conf.d directory within the contains folder, and load all files as settings.
In loading, hedzr/cmdr-loaders could parse the file format by its extension name. Some suffixes are:
- .toml
- .yaml, .yml
- .json
- .hjson
- .hcl
- .nestedtext, .txt, .conf
It's possible to mix all them up.
Write-Back the Changeset
For Alternative setting source, Write-Back machnism is supported: once the app terminating, the modified subset of app settings in memory will be written into Alternative file.
By default, only a <app-name>.{toml,yaml,...} in the current directory is Alternative setting source, thus it enables Write-Back automatically.
NOTE:
The file in <exeutable-dir>, another Alternative setting source, doesn't allow write-back.
Error Trace
The subcommand wrong gives a sample to show you how to return an error to top main() function.
And in DebugMode (enabled by cmdline --debug, checked by is.DebugMode()), our main() will print the stacktrace of the error. Here is it:
While a source raised an error without stacktrace info, likewise, the above log will miss them.
A fast and better solution is wrapping the err with hedzr/errors library. For a instance, the following codes show you how to wrap the error returned by go-git/v5, which is a simple stringerror object.
hedzr/errors.v3 is compliant with both of go1.11 - latest in theory. You can migrate from go1.13 errors to it smoothly.
The benefis of using hedzr/errors.v3 are:
errors.New(format, args...)can format message or attach objects in various ways,- nested errors / errors container
var ec = errors.New(); ec.Attach(err) - auto collecting stacktrace info
- more enhanced apis
How is this guide?
Last updated on