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)程序
參考URL: https://www.jianshu.com/p/790dc1171bbf
首先下載類庫包
go get github.com/urfave/cli
main.go
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管理方式
參考URL: https://studygolang.com/articles/2725
根據官網 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:
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)
}