Use command line flags in Go

There are many ways to use Go to handle the CLI logo. The first option is to not use any libraries at all, and then checkos.Args. The second option is to use the standard libraryflagpackage. The third option is to use one of many third-party CLI libraries, such ascobra.

Let's talk about the second option: use the standard libraryflag, Because it provides a lot of benefits compared to the original parsingos.ArgsIt is built-in.

Add toimport "flag"Go to the import part of the package and it's ready to use.

acceptintParameter Type:

func Int(name string, value int, usage string) *int

var count = flag.Int(“count”, 5, “the count of items”) fmt.Println("count value ", *count)

The first parameter is the flag name used in the CLI command, the second parameter is the default value, and the third parameter is the description.

Provides an alternative syntaxflag.IntVar():

func IntVar(p *int, name string, value int, usage string)

var count int flag.IntVar(&count, “count”, 5, “the count of items”) fmt.Println("count value ", count)

Here, the parameters are shifted, and the first parameter is the variable reference.

The main difference is that in the first case, you will get a pointer. In the second case, you can get value.

flagMany functions are provided to parse different types of logos. For each type you want to accept, you need to use different logos:

func Bool(name string, value bool, usage string) *bool
func BoolVar(p *bool, name string, value bool, usage string)
func Duration(name string, value time.Duration, usage string) *time.Duration
func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
func Float64(name string, value float64, usage string) *float64
func Float64Var(p *float64, name string, value float64, usage string)
func Int(name string, value int, usage string) *int
func Int64(name string, value int64, usage string) *int64
func Int64Var(p *int64, name string, value int64, usage string)
func IntVar(p *int, name string, value int, usage string)
func String(name string, value string, usage string) *string
func StringVar(p *string, name string, value string, usage string)
func Uint(name string, value uint, usage string) *uint
func Uint64(name string, value uint64, usage string) *uint64
func Uint64Var(p *uint64, name string, value uint64, usage string)
func UintVar(p *uint, name string, value uint, usage string)

Passing the wrong type for the flag will cause an error, halt the program, and the required usage will be printed to the user.

For example, here is how to parse a string:

var description = flag.String("description", "default value", "the description of the flag")

Logo grammar

How do you set the flag? Simple: additional-flagnameTo the CLI command, with 4 alternative but equivalent syntax:

-count=x
-count x
--count=x
--count x

You can pass as many flags to the command as you want, but this is the first timeflagUnable to recognize the flag, it will stop parsing other flags. This means that if you also have non-flag parameters, all flags must be at the beginning.

Parsing flag

After defining all the flags, you need to call

flag.Parse()

Actually parse them.

Boolean flag

Boolean flag can be set by adding-count, Which will give the boolean flagtruevalue. Set onefalseValue, use-count=false. Any of these values are valid for Boolean flags:1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False.

Short choice

In the real world, many times you will see a CLI application accepting a logo with a descriptive name and the same logo with a letter abbreviation. You can do this by providing 2 flag handlers:

var gopherType string

func init() { const ( defaultGopher = “pocket” usage = “the variety of gopher” ) flag.StringVar(&gopherType, “gopher_type”, defaultGopher, usage) flag.StringVar(&gopherType, “g”, defaultGopher, usage+" (shorthand)") }

Parse non-flag parameters

ThisflagThe package provides some methods to parse non-marked parameters.

flag.Args()

Returns a slice of the string whose argument is not parsed as a flag.

Mandatory marking as needed

ThisflagThe package does not provide a built-in solution to this problem. You need to handle this situation yourself:

// [...]
flag.Parse()

if *count == “” { flag.PrintDefaults() os.Exit(1) }

More advanced topics

This is an introductory article. You can enter more in-depth topics from here, such as implementing subcommands and defining your own logo types. Lookhttps://blog.komand.com/build-a-simple-cli-tool-with-golangMore advanced usage of CLI.

reference


More tutorials: