Go语言命令行库"gopkg.in/urfave/cli.v1"
很多go语言都使用这个来实现命令行操作,包括以太坊geth。用户只需要提供一些模块的配置、参数的解析、以及关联函数。其他在库内自动完成,并生成帮助信息。
举个例子想要实现这种命令行界面:
NAME:
GoFlag - flag test
USAGE:
___go_build_goflag_go.exe [global options] command [command options] [arguments...]
VERSION:
1.0.0
COMMANDS:
help, h Shows a list of commands or help for one command
arithmetic:
add, a calc 1+1
sub, s calc 5-3
database:
db database operations
GLOBAL OPTIONS:
--lang FILE, -l FILE read from FILE (default: "Chinese")
--port value, -p value listening port (default: 8080)
--help, -h Help!Help!
--print-version, -v print version
创建命令行实例:app := cli.NewApp()
配置命令行公共属性,名字,使用说明,版本:app.Name = "GoFlag" app.Usage = "flag test" app.Version = "1.0.0"
每一个具体int和string flag实例(-x调用),包括调用名字name以及逗号后的简写,默认值value,使用说明usage,变量值保存传递Destination:
app.Flags = []cli.Flag {
cli.IntFlag {
Name: "port, p",
Value: 8080,
Usage: "listening port",
},
cli.StringFlag {
Name: "lang, l",
Value: "Chinese",
Usage: "read from `FILE`",
Destination: &language,
},
}
命令行入口函数即什么都不输入或者只输入flag:
app.Action = func(c *cli.Context) error {
fmt.Println("BOOM!")
fmt.Println(c.String("lang"), c.Int("port"))
fmt.Println(language)
return nil
}
每一个具体命令调用(x调用),调用名字name,调用别名Aliases,使用说明Usage,分组目录Category,关联函数action,子命令Subcommands:
app.Commands = []cli.Command {
{
Name: "add",
Aliases: []string{"a"},
Usage: "calc 1+1",
Category: "arithmetic", //实现分组显示,同一值同一组
Action: func(c *cli.Context) error {
fmt.Println("1 + 1 = ", 1 + 1)
return nil
},
},
{
Name: "sub",
Aliases: []string{"s"},
Usage: "calc 5-3",
Category: "arithmetic",
Action: func(c *cli.Context) error {
fmt.Println("5 - 3 = ", 5 - 3)
return nil
},
},
{
Name: "db",
Usage: "database operations",
Category: "database",
Subcommands: []cli.Command {
{
Name: "insert",
Usage: "insert data",
Action: func(c *cli.Context) error {
fmt.Println("insert subcommand")
return nil
},
},
{
Name: "delete",
Usage: "delete data",
Action: func(c *cli.Context) error {
fmt.Println("delete subcommand")
return nil
},
},
},
},
}
command命令执行前操作:
app.Before = func(c *cli.Context) error {
fmt.Println("app Before")
return nil
}
command命令执行后操作:
app.After = func(c *cli.Context) error {
fmt.Println("app After")
return nil
}
flag按照字典顺序排列,而非声明顺序:
sort.Sort(cli.FlagsByName(app.Flags))
打印帮助信息:
cli.HelpFlag = cli.BoolFlag {
Name: "help, h",
Usage: "Help!Help!",
}
打印版本信息:
cli.VersionFlag = cli.BoolFlag {
Name: "print-version, v",
Usage: "print version",
}
读取参数运行命令行:
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
12.检查是否设置了全局配置文件路径flag的值,如果设置则读取该值
if ctx.GlobalIsSet(cmd.ConfigFileFlag.Name) {
configFn = ctx.GlobalString(cmd.ConfigFileFlag.Name) //如果设置了全局配置文件路径flag,则返回路径并赋值config
}
源码阅读原文,用法文档https://godoc.org/github.com/urfave/cli
希望大家关注我的微信公众号,有疑问可以后台留言。