以为这个问题不该该列出来,又以为若是初次进行WEB开发的话,可能会以为全部的东西均可以使用API去作,会以为命令行没有必要。
其实,一个生产的项目命令行是绕不过去的。好比运营须要导出报表、统计下付费用户、服务不稳定修改下订单状态等等,再者,命令行的工具基本都是内部使用,调试日志能够随意点,退一万步来讲,即便有问题了,还能够再次修改。不像API是是随机性的,有些业务发生错误和异常是随机的、不可逆的。git
这个主要看下使用案例就一目了然了。
首先下载类库包
go get github.com/urfave/cli
main.gogithub
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.goapp
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
执行命令看下结果ui
./test.bin test --uid=110 --username=feixiang 110 feixiang
就是这么简单
能够再看看子命令this
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日志