When writing a command line program, parsing command parameters is a common requirement. Various languages generally provide methods or libraries for parsing command-line parameters for the convenience of programmers. If the command-line parameters are written by themselves for code parsing, it will be quite difficult for the more complex ones. A package, flag, is provided in the Go standard library to facilitate command line parsing.
1. Read command line parameters
See the following command-line-arguments.go file
package main import "os" import "fmt" func main() { //os.Args provides raw command-line parameter access. Note that the first parameter in the slice is the path of the program, //And os.Args[1:] saves the parameters of all programs. argsWithProg := os.Args argsWithoutProg := os.Args[1:] //You can get the value of a single parameter using the standard index location method. arg := os.Args[3] fmt.Println(argsWithProg) fmt.Println(argsWithoutProg) fmt.Println(arg) } /* To experiment with command-line arguments, it's best to first compile an executable binary using go build $ go build command-line-arguments.go $ ./command-line-arguments a b c d [./command-line-arguments a b c d] [a b c d] c */
2. Basic implementation of command line flag
The command line flag is a common way for command line programs to specify options. For example, in wc -l, this - l is a command line flag.
package main // Go provides a flag package that supports basic command line flag parsing. We will use this package to implement our command line program example. import "flag" import "fmt" func main() { //The basic tag declaration supports only string, integer, and Boolean options. Here we declare a string flag word with a default value of "foo" and a short description. Here, the flag.String function returns a string pointer (not a string value). We will see how to use this pointer below. wordPtr := flag.String("word", "foo", "a string") //Declare the num and fork flags in the same way as the word flag. numbPtr := flag.Int("numb", 42, "an int") //The Bool type flag is a little special. Use - fork on the command line to set the value to true boolPtr := flag.Bool("fork", false, "a bool") //It is also possible to declare a flag with parameters already in the program. Note that a pointer to this parameter is required in the flag declaration function. var svar string flag.StringVar(&svar, "svar", "bar", "a string var") //After all flags are declared, call flag.Parse() to perform command line parsing. flag.Parse() //Here we will output only the parsed options and the following location parameters. Note that we need syntax like * wordPtr to dereference the pointer to get the actual value of the option. fmt.Println("word:", *wordPtr) fmt.Println("numb:", *numbPtr) fmt.Println("fork:", *boolPtr) fmt.Println("svar:", svar) fmt.Println("tail:", flag.Args()) } /* Before testing this program, it is best to compile it into a binary file and then run it. $ go build command-line-flags.go word: opt numb: 7 fork: true svar: flag tail: [] Note that if you omit a flag, its value is automatically set to its default value. $ ./command-line-flags -word=opt word: opt numb: 42 fork: false svar: bar tail: [] Position parameters can appear after any flag. $ ./command-line-flags -word=opt a1 a2 a3 word: opt ... tail: [a1 a2 a3] Note that the flag package requires all flags to appear before the location parameter (otherwise, the flag will be resolved to the location parameter). $ ./command-line-flags -word=opt a1 a2 a3 -numb=7 word: opt numb: 42 fork: false svar: bar trailing: [a1 a2 a3 -numb=7] Use the - h or -- help flag to get help text for this command-line program that is generated automatically. $ ./command-line-flags -h Usage of ./command-line-flags: -fork=false: a bool -numb=42: an int -svar="bar": a string var -word="foo": a string If you provide a flag that is not specified by the flag package, the program will output an error message and display the help text again. $ ./command-line-flags -wat flag provided but not defined: -wat Usage of ./command-line-flags: ... */
3. Advanced implementation of command line parameters
package main import ( "flag" "os" "log" "fmt" ) func printUsage() { fmt.Println("Usage:") fmt.Println("\taddblock -data DATA -- transaction data.") fmt.Println("\tprintchain -- Output block information.") } func isValidArgs() { if len(os.Args) < 2 { printUsage() os.Exit(1) } } func main() { isValidArgs() addBlockCmd := flag.NewFlagSet("addBlock",flag.ExitOnError) printChainCmd := flag.NewFlagSet("printchain",flag.ExitOnError) flagAddBlockData := addBlockCmd.String("data","http://liyuechun.org "," transaction data... ") switch os.Args[1] { case "addBlock": err := addBlockCmd.Parse(os.Args[2:]) if err != nil { log.Panic(err) } case "printchain": err := printChainCmd.Parse(os.Args[2:]) if err != nil { log.Panic(err) } default: printUsage() os.Exit(1) } if addBlockCmd.Parsed() { if *flagAddBlockData == "" { printUsage() os.Exit(1) } fmt.Println(*flagAddBlockData) } if printChainCmd.Parsed() { fmt.Println("Output data of all blocks........") } } //go build -o bc main.go //bc // ./bc addBlock -data "liyuechun.org" // ./bc printchain // About to output all block s