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 libraryflag
package. 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.Args
It is built-in.
Add toimport "flag"
Go to the import part of the package and it's ready to use.
acceptint
Parameter 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.
flag
Many 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-flagname
To 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 timeflag
Unable 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 flagtrue
value. Set onefalse
Value, 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
Thisflag
The 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
Thisflag
The 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
- https://golang.org/pkg/flag/
- https://thenewstack.io/cli-command-line-programming-with-go/
- https://blog.komand.com/build-a-simple-cli-tool-with-golang
More tutorials:
- Use NGINX reverse proxy service Go service
- Copy structure in Go
- Basics of Go web server
- Sorting map types in Go
- In a nutshell
- Go to label description
- Start date and time format
- Use Go for JSON processing
- Variadic function
- Cheat sheet
- Go to the empty interface description
- Use VS Code and Delve to debug Go
- Named Go return parameter
- Generate random numbers and strings in Go
- File system structure of Go project
- Binary search algorithm in Go
- Use command line flags in Go
- GOPATH explained
- Use Go to build a command line application: lolcat
- Use Go to build CLI commands: Cowsay
- Use shell and tube in Go
- Go CLI Tutorial: Fortune Clone
- Use Go to list files in a folder
- Use Go to get a list of repositories from GitHub
- Go, append a short string to the file
- Go, convert the string to byte slices
- Use Go to visualize your local Git contributions
- Getting started with Go CPU and memory analysis
- Solve the "Does not support index" error in the Go program
- Measuring the execution time in the Go program
- Use Go to build a web crawler to detect duplicate titles
- Best Practice: Pointer or Value Receiver?
- Best practice: Should you use methods or functions?
- Go data structure: set
- Go to the map cheat sheet
- Generating the implementation of generic types in Go
- Go data structure: dictionary
- Go data structure: hash table
- Implement event listeners in "through the channel"
- Go data structure: stack
- Go data structure: queue
- Go data structure: binary search tree
- Go data structure: graphics
- Go data structure: linked list
- A complete guide to Go data structures
- Compare Go value
- Is Go object-oriented?
- Use SQL database in Go
- Use environment variables in Go
- Last tutorial: REST API supported by PostgreSQL
- Enable CORS on the Go web server
- Deploy Go application in Docker container
- Why Go is a powerful language to learn as a PHP developer
- Go and delete the io.Reader.ReadString newline
- To start, how to watch the changes and rebuild the program
- To count the months since the date
- Access HTTP POST parameters in Go