前言
相信只要部署過(guò)線上服務(wù),都知道啟動(dòng)參數(shù)一定是必不可少的,當(dāng)你在不同的網(wǎng)絡(luò)、硬件、軟件環(huán)境下去啟動(dòng)一個(gè)服務(wù)的時(shí)候,總會(huì)有一些啟動(dòng)參數(shù)是不確定的,這時(shí)候就需要通過(guò)命令行模塊去解析這些參數(shù),urfave/cli是Golang中一個(gè)簡(jiǎn)單實(shí)用的命令行工具。
安裝
通過(guò) go get github.com/urfave/cli 命令即可完成安裝。
正文
使用了urfave/cli之后,你的程序就會(huì)變成一個(gè)命令行程序,以下就是通過(guò)urfave/cli創(chuàng)建的一個(gè)最簡(jiǎn)單的命令行程序,它設(shè)定了一些基礎(chǔ)的信息,這個(gè)程序的最終只是簡(jiǎn)單的打印了Test信息。
package main
import (
"github.com/urfave/cli"
"os"
"log"
"fmt"
)
func main() {
//實(shí)例化一個(gè)命令行程序
oApp := cli.NewApp()
//程序名稱
oApp.Name = "GoTool"
//程序的用途描述
oApp.Usage = "To save the world"
//程序的版本號(hào)
oApp.Version = "1.0.0"
//該程序執(zhí)行的代碼
oApp.Action = func(c *cli.Context) error {
fmt.Println("Test")
return nil
}
//啟動(dòng)
if err := oApp.Run(os.Args); err != nil {
log.Fatal(err)
}
/*
result:
[root@localhost cli]# go run main.go help
NAME:
GoTool - To save the world
USAGE:
main [global options] command [command options] [arguments...]
VERSION:
1.0.0
COMMANDS:
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--help, -h show help
--version, -v print the version
[root@localhost cli]# go run main.go
Test
*/
}
我們看到運(yùn)行 go run main.go help 之后會(huì)輸出一些幫助信息,說(shuō)明你的程序已經(jīng)成功成為一個(gè)命令行程序,接著使用命令 go run main.go 運(yùn)行這個(gè)程序,結(jié)果是打印了Test信息,所以這個(gè)程序?qū)嶋H運(yùn)行的函數(shù)由oApp.Action來(lái)控制,你后面的代碼應(yīng)該都在這個(gè)函數(shù)的內(nèi)部去實(shí)現(xiàn)。
接下來(lái)我們?cè)O(shè)定一些常見(jiàn)的啟動(dòng)參數(shù),非常的簡(jiǎn)單,代碼如下
package main
import (
"github.com/urfave/cli"
"os"
"log"
"fmt"
)
func main() {
//實(shí)例化一個(gè)命令行程序
oApp := cli.NewApp()
//程序名稱
oApp.Name = "GoTool"
//程序的用途描述
oApp.Usage = "To save the world"
//程序的版本號(hào)
oApp.Version = "1.0.0"
//預(yù)置變量
var host string
var debug bool
//設(shè)置啟動(dòng)參數(shù)
oApp.Flags = []cli.Flag{
//參數(shù)類型string,int,bool
cli.StringFlag{
Name: "host", //參數(shù)名字
Value: "127.0.0.1", //參數(shù)默認(rèn)值
Usage: "Server Address", //參數(shù)功能描述
Destination: host, //接收值的變量
},
cli.IntFlag{
Name: "port,p",
Value: 8888,
Usage: "Server port",
},
cli.BoolFlag{
Name: "debug",
Usage: "debug mode",
Destination: debug,
},
}
//該程序執(zhí)行的代碼
oApp.Action = func(c *cli.Context) error {
fmt.Printf("host=%v \n",host)
fmt.Printf("host=%v \n",c.Int("port")) //不使用變量接收,直接解析
fmt.Printf("host=%v \n",debug)
/*
result:
[root@localhost cli]# go run main.go --port 7777
host=127.0.0.1
host=7777
host=false
[root@localhost cli]# go run main.go help
NAME:
GoTool - To save the world
USAGE:
main [global options] command [command options] [arguments...]
VERSION:
1.0.0
COMMANDS:
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--host value Server Address (default: "127.0.0.1")
--port value, -p value Server port (default: 8888)
--debug debug mode
--help, -h show help
--version, -v print the version
*/
return nil
}
//啟動(dòng)
if err := oApp.Run(os.Args); err != nil {
log.Fatal(err)
}
}
執(zhí)行 go run main.go --port 7777 之后,可以看到輸出了設(shè)定的7777端口而非默認(rèn)的8888端口,而服務(wù)器地址(host)和調(diào)試模式(debug)都輸出了默認(rèn)的數(shù)值。
如果第三方人員第一次使用你的程序也可以通過(guò)help命令看到可以設(shè)定的參數(shù)都有哪些,非常的人性化。
當(dāng)然,urfave/cli還允許我們?cè)O(shè)置多個(gè)命令,不同的命令執(zhí)行不同的操作,具體如下
package main
import (
"github.com/urfave/cli"
"os"
"log"
"fmt"
)
func main() {
//實(shí)例化一個(gè)命令行程序
oApp := cli.NewApp()
//程序名稱
oApp.Name = "GoTool"
//程序的用途描述
oApp.Usage = "To save the world"
//程序的版本號(hào)
oApp.Version = "1.0.0"
//設(shè)置多個(gè)命令處理函數(shù)
oApp.Commands = []cli.Command{
{
//命令全稱
Name:"lang",
//命令簡(jiǎn)寫
Aliases:[]string{"l"},
//命令詳細(xì)描述
Usage:"Setting language",
//命令處理函數(shù)
Action: func(c *cli.Context) {
// 通過(guò)c.Args().First()獲取命令行參數(shù)
fmt.Printf("language=%v \n",c.Args().First())
},
},
{
Name:"encode",
Aliases:[]string{"e"},
Usage:"Setting encoding",
Action: func(c *cli.Context) {
fmt.Printf("encoding=%v \n",c.Args().First())
},
},
}
//啟動(dòng)
if err := oApp.Run(os.Args); err != nil {
log.Fatal(err)
}
/*
[root@localhost cli]# go run main.go l english
language=english
[root@localhost cli]# go run main.go e utf8
encoding=utf8
[root@localhost cli]# go run main.go help
NAME:
GoTool - To save the world
USAGE:
main [global options] command [command options] [arguments...]
VERSION:
1.0.0
COMMANDS:
lang, l Setting language
encode, e Setting encoding
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--help, -h show help
--version, -v print the version
*/
}
上面代碼只實(shí)現(xiàn)了兩個(gè)簡(jiǎn)單命令,兩個(gè)命令最后的處理函數(shù)不同,自然使用不同命令,最后的輸出也不一樣。
補(bǔ)充:Go語(yǔ)言命令行庫(kù)-urfave/cli(gopkg.in/urfave/cli.v2)
Go語(yǔ)言命令行庫(kù)-urfave/cli
官網(wǎng):https://github.com/urfave/cli
很多用Go寫的命令行程序都用了urfave/cli這個(gè)庫(kù)。urfave/cli是一個(gè)命令行的框架。
用C寫過(guò)命令行程序的人應(yīng)該都不陌生,我們需要根據(jù)argc/argv一個(gè)個(gè)地解析命令行參數(shù),調(diào)用不同的函數(shù),最后還要寫一個(gè)usage()函數(shù)用于打印幫助信息。urfave/cli把這個(gè)過(guò)程做了一下封裝,抽象出flag/command/subcommand這些模塊,用戶只需要提供一些模塊的配置,參數(shù)的解析和關(guān)聯(lián)在庫(kù)內(nèi)部完成,幫助信息也可以自動(dòng)生成。
總體來(lái)說(shuō),urfave/cli這個(gè)庫(kù)還是很好用的,完成了很多routine的工作,程序員只需要專注于具體業(yè)務(wù)邏輯的實(shí)現(xiàn)。
怎么使用urfave/cli
go如何編寫命令行(cli)程序
首先下載類庫(kù)包
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啟動(dòng)程序
app.Run(os.Args)
}
Flags 用于設(shè)置參數(shù)。
Action 對(duì)應(yīng)的函數(shù)就是你具體對(duì)各個(gè)參數(shù)具體的處理邏輯。
“gopkg.in/urfave/cli.v2” 和 “github.com/urfave/cli”
官網(wǎng):https://github.com/urfave/cli
gopkg:一種方便的go pakcage管理方式
根據(jù)官網(wǎng) readme描述,現(xiàn)在2個(gè)版本,主版本使用的是 v2 分支。
導(dǎo)入包為: “github.com/urfave/cli/v2”
有些 go 的代碼庫(kù)地址是gopkg.in開(kāi)頭的,比如gopkg.in/urfave/cli.v2。
v2 表明版本號(hào)為 v2,而代碼則為 github 上面相應(yīng)的 v2 branch。
這個(gè)也是 Go 的包管理解決方案之一,就是 gopkg.in 做了一個(gè)轉(zhuǎn)發(fā)過(guò)程,實(shí)際上是使用了 github 里面的相應(yīng)的 tag 的代碼
子命令 Subcommands
如下 demo所示,我們?cè)貯ction:同層添加 我們定義指針 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啟動(dòng)程序
app.Run(os.Args)
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- golang執(zhí)行命令操作 exec.Command
- golang執(zhí)行命令獲取執(zhí)行結(jié)果狀態(tài)(推薦)
- Golang命令行進(jìn)行debug調(diào)試操作
- golang中命令行庫(kù)cobra的使用方法示例
- 利用Golang如何調(diào)用Linux命令詳解
- Golang匯編命令解讀及使用