This is a creation in Article, where the information may have evolved or changed.
Original address
The CLI or "command line Interface" is a program that the user interacts with at the command prompt. Because it reduces dependencies by compiling programs into a static file, a go is particularly useful for developing CLI programs. If you write a CLI program that requires a variety of dependencies during installation, you know how important this is.
In this blog we will cover the basics of using go to develop the CLI.
Arguments
Most CLI programs need to enter some parameters. The Go language handles these parameters as String slice.
var Args []string
Find the name of the current app.
Package Mainimport ( "fmt" "os") func Main () { // program Name is always the first (implicit) argument cmd: = os. args[0] fmt. Printf ("programName:%s\n", cmd)}
This application is Code/example1, you can compile and run it with the command:
go build. /example1
The result of the output is:
Program Name:./example1
Determine the number of parameters for an incoming program
To determine how many parameters are passed in, you can calculate the length of all parameters minus 1 (remember, the first parameter is always the name of the program). Or it can be directly from the OS. Args[1:] to judge his length.
Package Mainimport ( "fmt" "os") func Main () { argcount:= Len (OS). args[1:]) FMT. Printf ("total Arguments (excluding program name):%d\n", Argcount)}
The result of running./example2 will be 0. Run./example2-foo=bar will get a demerit of 1.
Traversal parameters
The following is an example of a very fast traversal parameter.
Package Mainimport ("FMT" "OS") Func main () { forI, A: = Range OS. args[1:] {FMT. Printf ("Argument%d is%s\n", i+1, a)}} Running the program with./example3-local u=admin--help Resultsinch: Argument1 is-localargument2 isu=adminargument3 is--help
Flag Pack
So far we have known how to find the basic method of parameters in a program. It is cumbersome to query them at this level and assign them to our program. All we have is the flag pack.
Package Mainimport ("Flag" "FMT") Func main () {varPortintflag. Intvar (&port,"P",8000,"specify port to use. Defaults to 8000.") flag. Parse () fmt. Printf ("Port =%d", Port)}
The first thing we do is set the default value for an int type to be 8000, and there is a literal hint of the identity.
In order for the flag package to assign a value to the set variable, it is required to use flag. Parse () method.
The result of running this program without arguments is Port = 8000, because we explicitly specify that if no parameters are passed to port, the default of 8000 is used.
Run the./example4-p=9000 result is port = 9000
Colleague Flag provides the output of "program Useage". If we run./example4-help we will get:
Usage of./example4:-p=8000: Specify port to use. 8000.
Flag. Args ()
Many CLI programs contain both identified and non-identified parameters. Flag. Args () will return directly which parameters are not identified.
Package Mainimport ("Flag" "FMT") Func main () {varPortintflag. Intvar (&port,"P",8000,"specify port to use. Defaults to 8000.") flag. Parse () fmt. Printf ("Port =%d\n", Port) fmt. Printf ("Other args:%+v\n", Flag. Args ())}
Run./example5-p=9000 Foo=10-bar will get:
9000 Other args: [foo=ten -bar]
Flag stops the query as soon as it finds a flag that is not included.
Invalid flag parameter
Go is a strong language type, so if we pass a string to a flag of type int, it will prompt us to:
Package Mainimport ("Flag" "FMT") Func main () {varPortintflag. Intvar (&port,"P",8000,"specify port to use. Defaults to 8000") flag. Parse () fmt. Printf ("Port =%d", Port)}
Run the program./example6-p=foo results are as follows:
for flag-P:strconv. Parseint:parsing "foo": Invalid syntaxusage of. /example6:-p=8000: Specify port to use. 8000
Flag not only prompts us to enter errors, but also outputs the default usage.
Flag. Usage
The flag package declares a usage method. So we can output the usage we want to output.
Package Mainimport ("Flag" "FMT" "OS") Func main () {flag. Usage=func () {fmt. Printf ("Usage of%s:\n", OS. args[0]) fmt. Printf ("example7 file1 file2 ... \ n") flag. Printdefaults ()} flag. Parse ()}
The result of running./example7–help is:
Usage of./example7:example7 file1 file2 ...
Get input
So far we've just output information through the CLI, but we don't accept any input. We can base the FMT. SCANF () to capture the input.
Package Mainimport"FMT"Func Main () {varGuesscolorstring ConstFavcolor ="Blue" for{fmt. Println ("Guess My favorite color:") if_, Err: = FMT. SCANF ("%s", &guesscolor); Err! =Nil {fmt. Printf ("%s\n", Err)return } ifFavcolor = =Guesscolor {fmt. Printf ("%q is my favorite color!", Favcolor)return} fmt. Printf ("Sorry,%q is not my favorite color. Guess again.\n", Guesscolor)}}
Bufio. Scanner
Fmt. SCANF is useful for simple input, but sometimes we may need a whole row of data.
Package Mainimport ("Bufio" "FMT" "OS") Func main () {scanner:=Bufio. Newscanner (OS. Stdin) forscanner. Scan () {line:=scanner. Text ()ifline = ="Exit"{os. Exit (0)} FMT. Println (line)//Println would add back the final ' \ n ' } ifERR: = Scanner. ERR (); Err! =Nil {fmt. Fprintln (OS. Stderr,"reading standard input:", Err)}}
This is a basic echo program, if you want to exit the direct input exit.
A basic Cat program
You should have used the cat program many times. What we're going to learn from this blog is just a mix of building a basic cat program.
Package Mainimport ("Flag" "FMT" "io" "OS") Func main () {flag. Usage=func () {fmt. Printf ("Usage of%s:\n", OS. args[0]) fmt. Printf ("cat file1 file2 ... \ n") flag. Printdefaults ()} flag. Parse ()ifFlag. Narg () = =0{flag. Usage () OS. Exit (1) } for_, fn: =Range flag. Args () {f, err:=OS. Open (FN); ifErr! =Nil {panic (err)} _, Err=io. Copy (OS. Stdout, F)ifErr! =Nil {panic (err) }}}
Help
For help we've talked about it above but there's no definite definition
-H
Help
All of this will trigger help.
Summarize
This blog is just about some basic uses of the CLI. If you want to learn more, you can view the Godoc of these packages
Other command-line libraries
There are also third-party libraries that make it easier to write CLI programs: