nginx version: nginx/1.10.0Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]Options: -?,-h : this help -v : show version and exit -V : show version and configure options then exit -t : test configuration and exit -T : test configuration, dump it and exit -q : suppress non-error messages during configuration testing -s signal : send signal to a master process: stop, quit, reopen, reload -p prefix : set prefix path (default: /usr/local/nginx/) -c filename : set configuration file (default: conf/nginx.conf) -g directives : set global directives out of configuration file
我们通过 flag 实现类似 nginx 的这个输出,创建文件 nginx.go,内容如下:
package mainimport (\公众flag\公众\公众fmt\公众\"大众os\公众)// 实际中该当用更好的变量名var (h boolv, V boolt, T boolq bools stringp stringc stringg string)func init() {flag.BoolVar(&h, \"大众h\"大众, false, \"大众this help\"大众)flag.BoolVar(&v, \公众v\"大众, false, \公众show version and exit\公众)flag.BoolVar(&V, \公众V\公众, false, \"大众show version and configure options then exit\"大众)flag.BoolVar(&t, \公众t\"大众, false, \公众test configuration and exit\"大众)flag.BoolVar(&T, \公众T\公众, false, \"大众test configuration, dump it and exit\"大众)// 另一种绑定办法q = flag.Bool(\公众q\"大众, false, \"大众suppress non-error messages during configuration testing\公众)// 把稳 `signal`。默认是 -s string,有了 `signal` 之后,变为 -s signalflag.StringVar(&s, \公众s\公众, \"大众\公众, \公众send `signal` to a master process: stop, quit, reopen, reload\"大众)flag.StringVar(&p, \"大众p\公众, \"大众/usr/local/nginx/\公众, \"大众set `prefix` path\"大众)flag.StringVar(&c, \"大众c\"大众, \"大众conf/nginx.conf\"大众, \"大众set configuration `file`\公众)flag.StringVar(&g, \"大众g\"大众, \"大众conf/nginx.conf\"大众, \"大众set global `directives` out of configuration file\公众)// 改变默认的 Usageflag.Usage = usage}func main() {flag.Parse()if h {flag.Usage()}}func usage() {fmt.Fprintf(os.Stderr, `nginx version: nginx/1.10.0Usage: nginx [-hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]Options:`)flag.PrintDefaults()}
实行:go run nginx.go -h,(或 go build -o nginx && ./nginx -h)
输出如下:

flag 包概述
flag 包实现了命令行参数的解析。
定义 flags 有两种办法1)flag.Xxx(),个中 Xxx 可以是 Int、String 等;返回一个相应类型的指针,如:
var ip = flag.Int(\"大众flagname\公众, 1234, \"大众help message for flagname\"大众)
2)flag.XxxVar(),将 flag 绑定到一个变量上,如:
var flagvar intflag.IntVar(&flagvar, \"大众flagname\"大众, 1234, \"大众help message for flagname\"大众)自定义 Value
其余,还可以创建自定义 flag,只要实现 flag.Value 接口即可(哀求 receiver 是指针),这时候可以通过如下办法定义该 flag:
flag.Var(&flagVal, \"大众name\"大众, \"大众help message for flagname\公众)
例如,解析我喜好的编程措辞,我们希望直接解析到 slice 中,我们可以定义如下 Value:
type sliceValue []stringfunc newSliceValue(vals []string, p []string) sliceValue { p = vals return (sliceValue)(p)}func (s sliceValue) Set(val string) error { s = sliceValue(strings.Split(val, \"大众,\公众)) return nil}func (s sliceValue) Get() interface{} { return []string(s) }func (s sliceValue) String() string { return strings.Join([]string(s), \"大众,\"大众) }
之后可以这么利用:
var languages []stringflag.Var(newSliceValue([]string{}, &languages), \公众slice\"大众, \"大众I like programming `languages`\"大众)
这样通过 -slice \"大众go,php\"大众 这样的形式通报参数,languages 得到的便是 [go, php]。
flag 中对 Duration 这种非基本类型的支持,利用的便是类似这样的办法。
解析 flag在所有的 flag 定义完成之后,可以通过调用 flag.Parse() 进行解析。
命令行 flag 的语法有如下三种形式:
-flag // 只支持bool类型-flag=x-flag x // 只支持非bool类型
个中第三种形式只能用于非 bool 类型的 flag,缘故原由是:如果支持,那么对付这样的命令 cmd -x ,如果有一个文件名字是:0或false等,则命令的原融会改变(之以是这样,是由于 bool 类型支持 -flag 这种形式,如果 bool 类型不支持 -flag 这种形式,则 bool 类型可以和其他类型一样处理。也正由于这样,Parse()中,对 bool 类型进行了分外处理)。默认的,供应了 -flag,则对应的值为 true,否则为 flag.Bool/BoolVar 中指定的默认值;如果希望显示设置为 false 则利用 -flag=false。
int 类型可以是十进制、十六进制、八进制乃至是负数;bool 类型可以是1, 0, t, f, true, false, TRUE, FALSE, True, False。Duration 可以接管任何 time.ParseDuration 能解析的类型。
类型和函数在看类型和函数之前,先看一下变量。
ErrHelp:该缺点类型用于当命令行指定了 ·-help` 参数但没有定义时。Usage:这是一个函数,用于输出所有定义了的命令行参数和帮助信息(usage message)。一样平常,当命令行参数解析出错时,该函数会被调用。我们可以指定自己的 Usage 函数,即:flag.Usage = func(){}函数go标准库中,常常这么做:
定义了一个类型,供应了很多方法;为了方便利用,会实例化一个该类型的实例(通用),这样便可以直策应用该实例调用方法。比如:encoding/base64 中供应了 StdEncoding 和 URLEncoding 实例,利用时:base64.StdEncoding.Encode()
在 flag 包利用了有类似的方法,比如 CommandLine 实例,只不过 flag 进行了进一步封装:将 FlagSet 的方法都重新定义了一遍,也便是供应了一序列函数,而函数中只是大略的调用已经实例化好了的 FlagSet 实例:CommandLine 的方法。这样,利用者是这么调用:flag.Parse() 而不是 flag. CommandLine.Parse()。(Go 1.2 起,将 CommandLine 导出,之前是非导出的)
这里不详细先容各个函数,在类型方法中先容。
类型(数据构造)1)ErrorHandling
type ErrorHandling int
该类型定义了在参数解析出错时缺点处理办法。定义了三个该类型的常量:
const ( ContinueOnError ErrorHandling = iota ExitOnError PanicOnError)
三个常量在源码的 FlagSet 的方法 parseOne() 中利用了。
2)Flag
// A Flag represents the state of a flag.type Flag struct { Name string // name as it appears on command line Usage string // help message Value Value // value as set DefValue string // default value (as text); for usage message}
Flag 类型代表一个 flag 的状态。
比如,对付命令:./nginx -c /etc/nginx.conf,相应代码是:
flag.StringVar(&c, \公众c\"大众, \"大众conf/nginx.conf\"大众, \公众set configuration `file`\"大众)
则该 Flag 实例(可以通过 flag.Lookup(\公众c\"大众) 得到)相应各个字段的值为:
&Flag{ Name: c, Usage: set configuration file, Value: /etc/nginx.conf, DefValue: conf/nginx.conf,}
3)FlagSet
// A FlagSet represents a set of defined flags.type FlagSet struct { // Usage is the function called when an error occurs while parsing flags. // The field is a function (not a method) that may be changed to point to // a custom error handler. Usage func() name string // FlagSet的名字。CommandLine 给的是 os.Args[0] parsed bool // 是否实行过Parse() actual map[string]Flag // 存放实际通报了的参数(即命令行参数) formal map[string]Flag // 存放所有已定义命令行参数 args []string // arguments after flags // 开始存放所有参数,末了保留 非flag(non-flag)参数 exitOnError bool // does the program exit if there's an error? errorHandling ErrorHandling // 当解析出错时,处理缺点的办法 output io.Writer // nil means stderr; use out() accessor}
4)Value 接口
// Value is the interface to the dynamic value stored in a flag.// (The default value is represented as a string.)type Value interface { String() string Set(string) error}
所有参数类型须要实现 Value 接口,flag 包中,为int、float、bool等实现了该接口。借助该接口,我们可以自定义flag。(上文已经给了详细的例子)
紧张类型的方法(包括类型实例化)flag 包中紧张是 FlagSet 类型。
实例化办法NewFlagSet() 用于实例化 FlagSet。预定义的 FlagSet 实例 CommandLine 的定义办法:
// The default set of command-line flags, parsed from os.Args.var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
可见,默认的 FlagSet 实例在解析出错时会退出程序。
由于 FlagSet 中的字段没有 export,其他办法得到 FlagSet实例后,比如:FlagSet{} 或 new(FlagSet),该当调用Init() 方法,以初始化 name 和 errorHandling,否则 name 为空,errorHandling 为 ContinueOnError。
定义 flag 参数的方法这一序列的方法都有两种形式,在一开始已经说了两种办法的差异。这些方法用于定义某一类型的 flag 参数。
解析参数(Parse)func (f FlagSet) Parse(arguments []string) error
从参数列表中解析定义的 flag。方法参数 arguments 不包括命令名,即该当是os.Args[1:]。事实上,flag.Parse() 函数便是这么做的:
// Parse parses the command-line flags from os.Args[1:]. Must be called// after all flags are defined and before flags are accessed by the program.func Parse() { // Ignore errors; CommandLine is set for ExitOnError. CommandLine.Parse(os.Args[1:])}
该方法该当在 flag 参数定义后而详细参数值被访问前调用。
如果供应了 -help 参数(命令中给了)但没有定义(代码中没有),该方法返回 ErrHelp 缺点。默认的 CommandLine,在 Parse 出错时会退出程序(ExitOnError)。
为了更深入的理解,我们看一下 Parse(arguments []string) 的源码:
func (f FlagSet) Parse(arguments []string) error { f.parsed = true f.args = arguments for { seen, err := f.parseOne() if seen { continue } if err == nil { break } switch f.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(2) case PanicOnError: panic(err) } } return nil}
真正解析参数的方法是非导出方法 parseOne。
结合 parseOne 方法,我们来阐明 non-flag 以及包文档中的这句话:
Flag parsing stops just before the first non-flag argument (\"大众-\"大众 is a non-flag argument) or after the terminator \"大众--\公众.
我们须要理解解析什么时候停滞。根据 Parse() 中 for 循环终止的条件(不考虑解析出错),我们知道,当 parseOne 返回 false, nil 时,Parse 解析终止。正常解析完成我们不考虑。看一下 parseOne 的源码创造,有两处会返回 false, nil。
1)第一个 non-flag 参数
s := f.args[0]if len(s) == 0 || s[0] != '-' || len(s) == 1 { return false, nil}
也便是,当碰着单独的一个\"大众-\"大众或不是\公众-\"大众开始时,会停滞解析。比如:
./nginx - -c 或 ./nginx build -c
这两种情形,-c 都不会被精确解析。像该例子中的\"大众-\公众或build(以及之后的参数),我们称之为 non-flag参数。
2)两个连续的\"大众--\"大众
if s[1] == '-' { num_minuses++ if len(s) == 2 { // \"大众--\"大众 terminates the flags f.args = f.args[1:] return false, nil }}
也便是,当碰着连续的两个\"大众-\"大众时,解析停滞。
解释:这里说的\"大众-\"大众和\"大众--\"大众,位置和\"大众-c\"大众这种的一样。也便是说,下面这种情形并不是这里说的:
./nginx -c --
这里的\"大众--\"大众会被当成是 c 的值
parseOne 方法中接下来是处理 -flag=x 这种形式,然后是 -flag 这种形式(bool类型)(这里对bool进行了分外处理),接着是 -flag x 这种形式,末了,将解析成功的 Flag 实例存入 FlagSet 的 actual map 中。
其余,在 parseOne 中有这么一句:
f.args = f.args[1:]
也便是说,每实行成功一次 parseOne,f.args 会少一个。以是,FlagSet 中的 args 末了留下来的便是所有 non-flag 参数。
Arg(i int) 和 Args()、NArg()、NFlag()Arg(i int) 和 Args() 这两个方法便是获取 non-flag 参数的;NArg()得到 non-flag 的个数;NFlag() 得到 FlagSet 中 actual 长度(即被设置了的参数个数)。
1.4.5. Visit/VisitAll这两个函数分别用于访问 FlatSet 的 actual 和 formal 中的 Flag,而详细的访问办法由调用者决定。
PrintDefaults()打印所有已定义参数的默认值(调用 VisitAll 实现),默认输出到标准缺点,除非指定了 FlagSet 的 output(通过SetOutput() 设置)
Set(name, value string)设置某个 flag 的值(通过 name 查找到对应的 Flag)
1.5. 总结利用建议:虽然上面讲了那么多,一样平常来说,我们只大略的定义flag,然后 parse,就犹如开始的例子一样。
如果项目须要繁芜或更高等的命令行解析办法,可以利用 https://github.com/urfave/cli 或者 https://github.com/spf13/cobra 这两个强大的库。