脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - Golang中基础的命令行模块urfave/cli的用法说明

Golang中基础的命令行模块urfave/cli的用法说明

2021-03-05 00:48龙舞飞扬 Golang

这篇文章主要介绍了Golang中基础的命令行模块urfave/cli的用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

前言

相信只要部署过线上服务,都知道启动参数一定是必不可少的,当你在不同的网络、硬件、软件环境下去启动一个服务的时候,总会有一些启动参数是不确定的,这时候就需要通过命令行模块去解析这些参数,urfave/cliGolang中一个简单实用的命令行工具。

安装

通过 go get github.com/urfave/cli 命令即可完成安装。

正文

使用了urfave/cli之后,你的程序就会变成一个命令行程序,以下就是通过urfave/cli创建的一个最简单的命令行程序,它设定了一些基础的信息,这个程序的最终只是简单的打印了Test信息。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
 "github.com/urfave/cli"
 "os"
 "log"
 "fmt"
)
 
func main() {
 //实例化一个命令行程序
 oApp := cli.NewApp()
 //程序名称
 oApp.Name = "GoTool"
 //程序的用途描述
 oApp.Usage = "To save the world"
 //程序的版本号
 oApp.Version = "1.0.0"
 //该程序执行的代码
 oApp.Action = func(c *cli.Context) error {
 fmt.Println("Test")
 return nil
 }
 //启动
 if err := oApp.Run(os.Args); err != nil {
 log.Fatal(err)
 }
 /*
 result:
 [root@localhost cli]# go run main.go help
 
 NAME:
 GoTool - To save the world
 
 USAGE:
 main [global options] command [command options] [arguments...]
 
 VERSION:
 1.0.0
 
 COMMANDS:
 help, h Shows a list of commands or help for one command
 
 GLOBAL OPTIONS:
 --help, -h  show help
 --version, -v print the version
 
 [root@localhost cli]# go run main.go
 Test
 */
}

我们看到运行 go run main.go help 之后会输出一些帮助信息,说明你的程序已经成功成为一个命令行程序,接着使用命令 go run main.go 运行这个程序,结果是打印了Test信息,所以这个程序实际运行的函数由oApp.Action来控制,你后面的代码应该都在这个函数的内部去实现。

接下来我们设定一些常见的启动参数,非常的简单,代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
 "github.com/urfave/cli"
 "os"
 "log"
 "fmt"
)
 
func main() {
 //实例化一个命令行程序
 oApp := cli.NewApp()
 //程序名称
 oApp.Name = "GoTool"
 //程序的用途描述
 oApp.Usage = "To save the world"
 //程序的版本号
 oApp.Version = "1.0.0"
 
 //预置变量
 var host string
 var debug bool
 
 //设置启动参数
 oApp.Flags = []cli.Flag{
 //参数类型string,int,bool
 cli.StringFlag{
 Name:  "host",   //参数名字
 Value:  "127.0.0.1",  //参数默认值
 Usage:  "Server Address", //参数功能描述
 Destination: &host,   //接收值的变量
 },
 cli.IntFlag{
 Name:  "port,p",
 Value:  8888,
 Usage:  "Server port",
 },
 cli.BoolFlag{
 Name:  "debug",
 Usage:  "debug mode",
 Destination: &debug,
 },
 }
 
 //该程序执行的代码
 oApp.Action = func(c *cli.Context) error {
 fmt.Printf("host=%v \n",host)
 fmt.Printf("host=%v \n",c.Int("port")) //不使用变量接收,直接解析
 fmt.Printf("host=%v \n",debug)
 /*
 result:
 [root@localhost cli]# go run main.go --port 7777
 host=127.0.0.1
 host=7777
 host=false
 
 [root@localhost cli]# go run main.go help
 NAME:
  GoTool - To save the world
 
 USAGE:
  main [global options] command [command options] [arguments...]
 
 VERSION:
  1.0.0
 
 COMMANDS:
 help, h Shows a list of commands or help for one command
 
 GLOBAL OPTIONS:
  --host value   Server Address (default: "127.0.0.1")
  --port value, -p value Server port (default: 8888)
  --debug     debug mode
  --help, -h    show help
  --version, -v   print the version
 */
 return nil
 }
 //启动
 if err := oApp.Run(os.Args); err != nil {
 log.Fatal(err)
 }
}

执行 go run main.go --port 7777 之后,可以看到输出了设定的7777端口而非默认的8888端口,而服务器地址(host)和调试模式(debug)都输出了默认的数值。

如果第三方人员第一次使用你的程序也可以通过help命令看到可以设定的参数都有哪些,非常的人性化。

当然,urfave/cli还允许我们设置多个命令,不同的命令执行不同的操作,具体如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
 "github.com/urfave/cli"
 "os"
 "log"
 "fmt"
)
 
func main() {
 //实例化一个命令行程序
 oApp := cli.NewApp()
 //程序名称
 oApp.Name = "GoTool"
 //程序的用途描述
 oApp.Usage = "To save the world"
 //程序的版本号
 oApp.Version = "1.0.0"
 
 //设置多个命令处理函数
 oApp.Commands = []cli.Command{
 {
 //命令全称
 Name:"lang",
 //命令简写
 Aliases:[]string{"l"},
 //命令详细描述
 Usage:"Setting language",
 //命令处理函数
 Action: func(c *cli.Context) {
 // 通过c.Args().First()获取命令行参数
 fmt.Printf("language=%v \n",c.Args().First())
 },
 },
 {
 Name:"encode",
 Aliases:[]string{"e"},
 Usage:"Setting encoding",
 Action: func(c *cli.Context) {
 fmt.Printf("encoding=%v \n",c.Args().First())
 },
 },
 }
 
 //启动
 if err := oApp.Run(os.Args); err != nil {
 log.Fatal(err)
 }
 
 /*
 [root@localhost cli]# go run main.go l english
 language=english
 
 [root@localhost cli]# go run main.go e utf8
 encoding=utf8
 
 [root@localhost cli]# go run main.go help
 NAME:
 GoTool - To save the world
 
 USAGE:
 main [global options] command [command options] [arguments...]
 
 VERSION:
 1.0.0
 
 COMMANDS:
 lang, l Setting language
 encode, e Setting encoding
 help, h Shows a list of commands or help for one command
 
 GLOBAL OPTIONS:
 --help, -h  show help
 --version, -v print the version
 */
}

上面代码只实现了两个简单命令,两个命令最后的处理函数不同,自然使用不同命令,最后的输出也不一样。

补充:Go语言命令行库-urfave/cli(gopkg.in/urfave/cli.v2)

Go语言命令行库-urfave/cli

官网:https://github.com/urfave/cli

很多用Go写的命令行程序都用了urfave/cli这个库。urfave/cli是一个命令行的框架。

用C写过命令行程序的人应该都不陌生,我们需要根据argc/argv一个个地解析命令行参数,调用不同的函数,最后还要写一个usage()函数用于打印帮助信息。urfave/cli把这个过程做了一下封装,抽象出flag/command/subcommand这些模块,用户只需要提供一些模块的配置,参数的解析和关联在库内部完成,帮助信息也可以自动生成。

总体来说,urfave/cli这个库还是很好用的,完成了很多routine的工作,程序员只需要专注于具体业务逻辑的实现。

怎么使用urfave/cli

go如何编写命令行(cli)程序

首先下载类库包

go get github.com/urfave/cli

main.go

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main
import (
 "os"
 "github.com/urfave/cli/v2"
 "fmt"
)
func main() {
 app := &cli.App{
 Name: "greet",
 Usage: "say a greeting",
 Action: func(c *cli.Context) error {
 fmt.Println("Greetings")
 return nil
 },
 }
 // 接受os.Args启动程序
 app.Run(os.Args)
}

Flags 用于设置参数。

Action 对应的函数就是你具体对各个参数具体的处理逻辑。

“gopkg.in/urfave/cli.v2” 和 “github.com/urfave/cli”

官网:https://github.com/urfave/cli

gopkg:一种方便的go pakcage管理方式

根据官网 readme描述,现在2个版本,主版本使用的是 v2 分支。

导入包为: “github.com/urfave/cli/v2”

有些 go 的代码库地址是gopkg.in开头的,比如gopkg.in/urfave/cli.v2。

v2 表明版本号为 v2,而代码则为 github 上面相应的 v2 branch。

这个也是 Go 的包管理解决方案之一,就是 gopkg.in 做了一个转发过程,实际上是使用了 github 里面的相应的 tag 的代码

子命令 Subcommands

如下 demo所示,我们再Action:同层添加 我们定义指针 &cli.Command 变量即可。

demo:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var daemonStopCmd = &cli.Command{
 Name: "stop",
 Usage: "Stop a running lotus daemon",
 Flags: []cli.Flag{},
 Action: func(cctx *cli.Context) error {
 panic("wombat attack")
 },
}
func main() {
 app := &cli.App{
 Name: "greet",
 Usage: "say a greeting",
 Action: func(c *cli.Context) error {
 fmt.Println("Greetings")
 return nil
 },
 Subcommands: []*cli.Command{
 daemonStopCmd,
 },
 }
 // 接受os.Args启动程序
 app.Run(os.Args)
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/sd653159/article/details/83381786

延伸 · 阅读

精彩推荐
  • Golanggo语言获取系统盘符的方法

    go语言获取系统盘符的方法

    这篇文章主要介绍了go语言获取系统盘符的方法,涉及Go语言调用winapi获取系统硬件信息的技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    无尽海3862020-04-24
  • Golang深入浅析Go中三个点(...)用法

    深入浅析Go中三个点(...)用法

    这篇文章主要介绍了深入浅析Go中三个点(...)用法,需要的朋友可以参考下...

    踏雪无痕SS6472021-11-17
  • GolangGolang 语言极简类型转换库cast的使用详解

    Golang 语言极简类型转换库cast的使用详解

    本文我们通过 cast.ToString() 函数的使用,简单介绍了cast 的使用方法,除此之外,它还支持很多其他类型,在这没有多多介绍,对Golang 类型转换库 cast相关知...

    Golang语言开发栈6112021-12-02
  • GolangGolang实现四种负载均衡的算法(随机,轮询等)

    Golang实现四种负载均衡的算法(随机,轮询等)

    本文介绍了示例介绍了Golang 负载均衡的四种实现,主要包括了随机,轮询,加权轮询负载,一致性hash,感兴趣的小伙伴们可以参考一下...

    Gundy_8442021-08-09
  • GolangGo语言range关键字循环时的坑

    Go语言range关键字循环时的坑

    今天小编就为大家分享一篇关于Go语言range关键字循环时的坑,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来...

    benben_20154202020-05-23
  • GolangGo语言基础单元测试与性能测试示例详解

    Go语言基础单元测试与性能测试示例详解

    这篇文章主要为大家介绍了Go语言基础单元测试与性能测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助祝大家多多进步...

    枫少文7812021-12-05
  • GolangGo语言实现自动填写古诗词实例代码

    Go语言实现自动填写古诗词实例代码

    这篇文章主要给大家介绍了关于Go语言实现自动填写古诗词的相关资料,这是最近在项目中遇到的一个需求,文中通过示例代码介绍的非常详细,需要的朋...

    FengY5862020-05-14
  • GolangGO语言字符串处理Strings包的函数使用示例讲解

    GO语言字符串处理Strings包的函数使用示例讲解

    这篇文章主要为大家介绍了GO语言字符串处理Strings包的函数使用示例讲解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加...

    Jeff的技术栈6882022-04-14