Go Cmder combine Cobra and Viper to auto generate command-line tool where the user can control configuration in a precedence order: flags > environment variables > configuration files and the defaults defined by the config.
This library was inspired by Sting of the viper article from Carolyn Van Slyck.
go get github.com/ergagnon/gocmder
Supported tags:
desc
: used for the Flag description.default
: default value used in Flag and Viper config. Supported value type:string
,int
,float32
,bool
required
: set a required Flag.hidden
: don't create a Flag when hidden is true.
Example:
type AppConfig struct {
Directory string `desc:"Directory to browse" default:"."`
Server ServerConfig // support multi-level config
}
type ServerConfig struct {
Url string `desc:"Server url" default:"localhost"`
Port int `desc:"Username" default:"8080"`
}
Call the function
func NewCmder(cfg any, onFinalize OnFinalizeFunc, opts ...CmderOption) (*Cmder, error)
cli, err := gocmder.NewCmder(AppConfig{}, func(cfg any) error {
// At this step, the config object has been filled
// with all the values.
// You can use it in your application.
return nil
})
This will auto-generate
Flags:
Usage:
[flags]
Flags:
--directory string Directory to browse (default ".")
-h, --help help for this command
--server-port int Username (default 8080)
--server-url string Server url (default "localhost")
Environment Variable
DIRECTORY
SERVER_PORT
SERVER_URL
Config file (optional)
Configuration will use Viper defaults.
reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
Yaml example:
directory: "my_dir"
server:
url: "127.0.0.1"
port: 8080