golang开发:类库篇(三)命令行工具cli的使用

为什么要使用命令行

觉得这个问题不应该列出来,又觉得如果初次进行WEB开发的话,可能会觉得所有的东西都可以使用API去做,会觉得命令行没有必要。
其实,一个生产的项目命令行是绕不过去的。比如运营需要导出报表、统计下付费用户、服务不稳定修改下订单状态等等,再者,命令行的工具基本都是内部使用,调试日志可以随意点,退一万步来说,即使有问题了,还可以再次修改。不像API是是随机性的,有些业务发生错误和异常是随机的、不可逆的。

怎么使用cli

这个主要看下使用案例就一目了然了。
首先下载类库包
go get github.com/urfave/cli
main.go

package main

import (
	"fmt"
	"os"
	"github.com/urfave/cli"
)

func main() {
	app := cli.NewApp()
	app.Commands = []cli.Command{
		{
			Name:  "test",
			Usage: "test --uid=x --username=y",
			Action: (&Command{}).Test,
			Flags: []cli.Flag{
				cli.IntFlag{Name: "uid",Usage:"--uid"},
				cli.StringFlag{Name:"username",Usage:"--username"},
			},
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		fmt.Print("command error :" + err.Error())
	}
}

command.go

package main

import (
	"fmt"
	"github.com/urfave/cli"
)
type Command struct {
}

func (this *Command) Test(cli *cli.Context) {
	uid := cli.Int("uid")
	username := cli.String("username")
	fmt.Println(uid,username)
}

编译运行

go build -o test.bin
./test.bin
NAME:
   test.bin - A new cli application

USAGE:
   test.bin [global options] command [command options] [arguments...]

VERSION:
   0.0.0

COMMANDS:
     test     test --uid=x --username=y
     help, h  Shows a list of commands or help for one command

执行命令看下结果

./test.bin  test --uid=110 --username=feixiang
110 feixiang

就是这么简单
可以再看看子命令

func main() {
	app := cli.NewApp()
	app.Commands = []cli.Command{
		{
			Name:  "test",
			Usage: "test1 --uid=x --username=y|test2 --uid=x --username=y",
			Subcommands:[]cli.Command{
				{
					Name:  "test1",
					Usage: "test1 --uid=x --username=y",
					Action: (&Command{}).Test,
					Flags: []cli.Flag{
						cli.IntFlag{Name: "uid",Usage:"--uid"},
						cli.StringFlag{Name:"username",Usage:"--username"},
					},
				},
				{
					Name:  "test2",
					Usage: "test2 --uid=x --username=y",
					Action: (&Command{}).Test,
					Flags: []cli.Flag{
						cli.IntFlag{Name: "uid",Usage:"--uid"},
						cli.StringFlag{Name:"username",Usage:"--username"},
					},
				},
			},
		},
	}
	err := app.Run(os.Args)
	if err != nil {
		fmt.Print("command error :" + err.Error())
	}
}

编译运行看下结果

go build -o test.bin
./test.bin test test1 --uid=111 --username=hello
111 hello
./test.bin test test2 --uid=111 --username=hello
111 hello

就是再加了一层命令

命令行的使用比较简单。基本也没有需要注意的。
如果需要了解更详细的使用,看下文档
https://github.com/urfave/cli

posted @ 2019-07-14 19:06  飞翔码农  阅读(4528)  评论(1编辑  收藏  举报