golang executable file help settings

pflag.UsageImplement custom use help

  •  Define parameters
var (
	host          string
	user          string
	port          int
	password      string
	
)
  •  pflag is an alternative plug-in to the Go flag package, which implements POSIX/GNU style flags , basically the same as the "flag" package
  • github.com/spf13/pflag
  • Default flag:--
pflag.Usage = func() {
		
		pflag.PrintDefaults()
	}
	pflag.ErrHelp = errors.New("")
	pflag.StringVarP(&host, "host", "h", "127.0.0.1", "The host to connect to db")
	pflag.StringVarP(&password, "password", "p", "", "User password")
	pflag.IntVarP(&port, "port", "P", 26257, "TCP/IP port")
	pflag.StringVarP(&user, "user", "u", "root", "Username")

    // 在帮助文档中隐藏参数 user
	pflag.CommandLine.MarkHidden("user")
    // 传递的命令行参数解析为对应变量的值
	pflag.Parse()
  •  Parameters of type bool:
--flag               // 等同于 --flag=true        
--flag=value         // 建议写法
--flag value         // 只有在没有设置默认值时才生效

NoOptDefVal usage

The pflag package supports a simple way to set a value other than the default value for the parameter, the implementation method is to set the NoOptDefVal property of the parameter:

flag.Lookup("user").NoOptDefVal = "root"

 After go build, directly main.go -h can view the effect.

 

Guess you like

Origin blog.csdn.net/feikillyou/article/details/110485801