cflag - wraps and extends Go flag build pertty CLI command
cflag - wraps and extends Go flag build pertty CLI command
Use Go flag
Go flag is a package built into Go, and it is very easy to build a command application using the flag package.
package main
import (
"flag"
"os"
"github.com/gookit/goutil/cliutil"
"github.com/gookit/goutil/dump"
)
var opts1 = struct
// go run ./_example/rawflag.go
// go run ./cflag/_example/rawflag.go -h
func main()
func handleFunc1()
Show help

Some problems
It’s a package built into Go, and it’s very simple to use. But there are some problems:
- Adding short options to options is not supported
- Does not support parsing subsequent parameter information
- Can’t check if option is empty
- Rendering help information is very rudimentary
Use cflag
cflag - Wraps and extends go flag.FlagSet to build simple command line applications
- As easy as Go
flagto use - Supports auto-rendering of pretty help messages
- Allows adding short options to flag options, and multiples
- Allows binding named parameters
- Allows setting arguments or options as required
- Allows setting validators for arguments or options
Install
Usage example
cflag has the same binding option information as Go flag. At the same time, some additional information has been added, such as version, description, etc.
package main
import (
"os"
"github.com/gookit/goutil/cflag"
"github.com/gookit/goutil/cliutil"
)
var opts = struct
// go run ./_example/cmd.go
// go run ./cflag/_example/cmd.go -h
// go run ./cflag/_example/cmd.go --name inhere -a 12 --lo val ab cd
func main()
func handleFunc(c *cflag.CFlags) error
Set required and shortcuts
Option can be set as required(required), and supports setting short option name.
TIPs: Implement
requiredandshortsby extendingusagethat parses options
usage format
- Defatul:
desc - Foramt 1:
desc;required - Foramt 2:
desc;required;shorts required: A boolean string. Mark option is required- True:
true,on,yes - False:
false,off,no,''
- True:
shorts: Shortcut names for options, multiple values are allowed, separated by commas,
Examples:
// set option 'name' is required
c.StringVar(&opts.name, "name", "", "this is a string option and required;true")
// set option 'str1' shorts: s
c.StringVar(&opts.str1, "str1", "def-val", "this is a string option with default value;;s")
Binding and get arguments
Binding arguments
c.AddArg("arg1", "this is arg1", true, nil)
c.AddArg("arg2", "this is arg2", true, nil)
Get arguments by name
cliutil.Infoln("arg1 =", c.Arg("arg1").String())
cliutil.Infoln("arg2 =", c.Arg("arg2").Int())
Show help
Output:

Run command
Output:

required check
Output:
