為什么要使用命令行
覺得這個問題不應該列出來,又覺得如果初次進行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