使用 urfave/cli 解析命令行参数
chenzuoqing Lv3

使用 urfave/cli 解析命令行参数

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
package main

import (
"fmt"
"log"
"os"

"github.com/urfave/cli/v2"
)

var host string

func main() {
app := cli.NewApp()
app.Name = "Cli Test Application"
app.Usage = "cli test app usage"
app.Version = "1.1.0"
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "host",
Value: "127.0.0.1",
Usage: "host address",
Destination: &host, // 参数解析到 host 变量中
},
&cli.Int64Flag{
Name: "port",
Value: 10202,
Usage: "port number",
},
}
// 执行单个命令用 Action
// app.Action = func(c *cli.Context) error {
// fmt.Println("hello world")
// fmt.Println("host=", host)
// fmt.Println("port=", c.Int("port")) // 从 cli 中获取 port 参数
// return nil
// }

// 多个命令,可以指定到 Commands 中
app.Commands = []*cli.Command{
{
Name: "server",
Aliases: []string{"s"},
Usage: "run server",
Action: func(c *cli.Context) error {
fmt.Println("run server arg:", c.Args().First())
return nil
},
},
{
Name: "agent",
Aliases: []string{"a"},
Usage: "run agent",
Action: func(c *cli.Context) error {
fmt.Println("run agent arg:", c.Args().First())
return nil
},
},
}

if err := app.Run(os.Args); err != nil {
log.Fatalf("error: %v", err)
}
}

测试

1
2
3
4
5
6
# 单个命令的 Action 测试
go run cli.go --host 1.2.3.4 --port 11022

# 多入口命令测试
go run cli.go server start
go run cli.go agent stop
 Comments