在写命令行程序(工具、server)时,对命令参数进行解析是常见的需求。各种语言一般都会提供解析命令行参数的方法或库,以方便程序员使用。如果命令行参数纯粹自己写代码解析,对于比较复杂的,还是挺费劲的。在 go 标准库中提供了一个包:flag,方便进行命令行解析。

注:区分几个概念
    命令行参数(或参数):是指运行程序提供的参数已定义命令行参数:是指程序中通过flag.Xxx等这种形式定义了的参数非flag(non-flag)命令行参数(或保留的命令行参数):后文解释
使用示例

我们以 nginx 为例,执行 nginx -h,输出如下:

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
相关文章