Most Go programs have no UI, and run in the pure command line mode, what to do depends on the runtime parameters. Here is a detailed explanation of the command line programs and parameters of the Go language.
1st Args
Programs can obtain runtime parameters through the os package, examples are as follows:
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
for idx, args := range os.Args {
fmt.Println("参数" + strconv.Iota(idx) + ":" args)
}
}
Run to get the following results:
$ go run os_flat.go 1 false —a ? -
参数0:/var/folders/jd/_nrr3p2x5pncw4y0trf_0bq40000gn/T/go-build1510265706/b001/exe/os_flat
参数1:1
参数2:false
参数3:—a
参数4:?
参数5:-
It can be seen that the command line parameters include the program path itself, as well as parameters in the usual sense.
In the program, the os.Args type is []string, which is a string slice. So you can use the for range loop to traverse, and you can also use len(os.Args) to get all the parameters.
If you don't want to output information about the executable itself, you can slice it.
for idx, args := range os.Args[1:] {
}
There is a more concise way to output all elements of a slice:
fmt.Println(strings.Join(os.Args[1:0]), "\n")
fmt.Println(os.Args[1:]) // [1 false —a ? -] 这是fmt.Println输出切片的格式
2. flag package
os.Args
The flag package provides stronger capabilities than simply analyzing command line parameters through slices.
When writing command-line programs, parsing command-line parameters is a common requirement. Various languages generally provide methods or libraries for parsing command line parameters for the convenience of programmers. A package is provided in the go standard library: flag, which is convenient for command line parsing. The method like String()
or StringVar()
only associates parameters such as the parameter name, the memory address of the received value, and the default value, and does not actually register the parsing of arguments to the flag. Therefore, it must be called after defining and receiving flag parameters and before accessing these parameters flag.Parse()
.
package main
import (
"fmt"
"flag"
)
func main() {
// 定义几个变量,用于接收命令行参数值
var user string
var pwd string
var host string
var port int
// &user 用来接收命令行中输入的 -u 后面的参数值
// "u" 就是 -u 指定的参数
// "" 默认值
// “用户名,默认为空” 说明
flag.StringVar(&user, "u", "", "用户名,默认为空")
flag.StringVar(&pwd, "pwd", "", "密码,默认为空")
flag.StringVar(&host, "h", "localhost", "主机名,默认为localhost")
flag.IntVar(&port, "port", 3306, "端口号,默认3306")
// 【必须调用】 从arguments 中解析注册到flag
flag.Parse()
// 输出结果
fmt.Printf("\n user = %v \n pwd=%v \n host=%v \n port=%v \n", user, pwd, host, port)
}
Either way works:
$ go run go_flag.go -u 111 -pwd 222 -h 127.0.0.1 -port 222
user=111
pwd=222
host=127.0.0.1
port=222
$ go run go_flag.go -u=111 -pwd=222 -h=127.0.0.1 -port=222
user=111
pwd=222
host=127.0.0.1
port=222
flag package usage guide
-
define parameters
To use the flag package, first define the command line parameters to be parsed, that is, the parameters starting with "-", such as "-u -pwd" above. -help does not need to be specified, it can be handled automatically.
func StringVar(p *string, name string, value string, usage string) { } func IntVar(p *int, name string, value int, usage string) { }
Both functions have 4 parameters, which are the address of the parameter to be received, the name of the command line parameter, the default value, and the prompt string.
-
parsing parameters
Before the flag is used, it must be parsed first.
flag.Parse()
-
use parameters
As shown above, you can directly use
-
Unparsed parameter
If there is any part of the parameters that is not parsed according to the predefined parameters, it
flag.Args()
can be obtained through , which is a string slice.
fmt.Println("其他参数:, flat.Args()")
It should be noted that starting from the first parameter that cannot be parsed, all subsequent parameters cannot be parsed. Even if the following parameters contain predefined parameters.
package main
import (
"fmt"
"flag"
)
var b = flag.Bool("b", false, "布尔型参数")
var s = flag.String("s", "", "字符串类型参数")
func main() {
flag.Parse()
fmt.Println("-b", *b)
fmt.Println("-s", *s)
fmt.Println("其他参数", flag.Args())
}
With different parameters, the execution results are as follows:
----------------
$ go run flag1.go
-b false
-s
其他参数 []
----------------
$ go run flag1.go -b
-b true
-s
其他参数 []
----------------
$ go run flag1.go -b -s woshishei other
-b true
-s woshishei
其他参数 [other]
----------------
age of /var/folders/jd/_nrr3p2x5pncw4y0trf_0bq40000gn/T/go-build1422013025/b001/exe/flag1:
-b 布尔型参数
-s string
字符串类型参数
----------------
$ go run flag1.go -b sss -s woshishei other
-b true
-s
其他参数 [sss -s woshishei other]
----------------