佳木斯湛栽影视文化发展公司

主頁 > 知識(shí)庫 > Golang中基礎(chǔ)的命令行模塊urfave/cli的用法說明

Golang中基礎(chǔ)的命令行模塊urfave/cli的用法說明

熱門標(biāo)簽:地方門戶網(wǎng)站 AI電銷 服務(wù)外包 網(wǎng)站排名優(yōu)化 鐵路電話系統(tǒng) 呼叫中心市場需求 Linux服務(wù)器 百度競價(jià)排名

前言

相信只要部署過線上服務(wù),都知道啟動(dòng)參數(shù)一定是必不可少的,當(dāng)你在不同的網(wǎng)絡(luò)、硬件、軟件環(huán)境下去啟動(dòng)一個(gè)服務(wù)的時(shí)候,總會(huì)有一些啟動(dòng)參數(shù)是不確定的,這時(shí)候就需要通過命令行模塊去解析這些參數(shù),urfave/cli是Golang中一個(gè)簡單實(shí)用的命令行工具。

安裝

通過 go get github.com/urfave/cli 命令即可完成安裝。

正文

使用了urfave/cli之后,你的程序就會(huì)變成一個(gè)命令行程序,以下就是通過urfave/cli創(chuàng)建的一個(gè)最簡單的命令行程序,它設(shè)定了一些基礎(chǔ)的信息,這個(gè)程序的最終只是簡單的打印了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ì)輸出一些幫助信息,說明你的程序已經(jīng)成功成為一個(gè)命令行程序,接著使用命令 go run main.go 運(yùn)行這個(gè)程序,結(jié)果是打印了Test信息,所以這個(gè)程序?qū)嶋H運(yùn)行的函數(shù)由oApp.Action來控制,你后面的代碼應(yīng)該都在這個(gè)函數(shù)的內(nèi)部去實(shí)現(xiàn)。

接下來我們?cè)O(shè)定一些常見的啟動(dòng)參數(shù),非常的簡單,代碼如下

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ù)值。

如果第三方人員第一次使用你的程序也可以通過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",
 //命令簡寫
 Aliases:[]string{"l"},
 //命令詳細(xì)描述
 Usage:"Setting language",
 //命令處理函數(shù)
 Action: func(c *cli.Context) {
 // 通過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è)簡單命令,兩個(gè)命令最后的處理函數(shù)不同,自然使用不同命令,最后的輸出也不一樣。

補(bǔ)充:Go語言命令行庫-urfave/cli(gopkg.in/urfave/cli.v2)

Go語言命令行庫-urfave/cli

官網(wǎng):https://github.com/urfave/cli

很多用Go寫的命令行程序都用了urfave/cli這個(gè)庫。urfave/cli是一個(gè)命令行的框架。

用C寫過命令行程序的人應(yīng)該都不陌生,我們需要根據(jù)argc/argv一個(gè)個(gè)地解析命令行參數(shù),調(diào)用不同的函數(shù),最后還要寫一個(gè)usage()函數(shù)用于打印幫助信息。urfave/cli把這個(gè)過程做了一下封裝,抽象出flag/command/subcommand這些模塊,用戶只需要提供一些模塊的配置,參數(shù)的解析和關(guān)聯(lián)在庫內(nèi)部完成,幫助信息也可以自動(dòng)生成。

總體來說,urfave/cli這個(gè)庫還是很好用的,完成了很多routine的工作,程序員只需要專注于具體業(yè)務(wù)邏輯的實(shí)現(xiàn)。

怎么使用urfave/cli

go如何編寫命令行(cli)程序

首先下載類庫包

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 的代碼庫地址是gopkg.in開頭的,比如gopkg.in/urfave/cli.v2。

v2 表明版本號(hào)為 v2,而代碼則為 github 上面相應(yīng)的 v2 branch。

這個(gè)也是 Go 的包管理解決方案之一,就是 gopkg.in 做了一個(gè)轉(zhuǎn)發(fā)過程,實(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中命令行庫cobra的使用方法示例
  • 利用Golang如何調(diào)用Linux命令詳解
  • Golang匯編命令解讀及使用

標(biāo)簽:黃山 崇左 湘潭 湖南 蘭州 仙桃 銅川 衡水

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Golang中基礎(chǔ)的命令行模塊urfave/cli的用法說明》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    巧家县| 黎川县| 新巴尔虎左旗| 融水| 新余市| 宝丰县| 湖北省| 会同县| 息烽县| 凤台县| 清河县| 贺州市| 孙吴县| 黔东| 扶绥县| 贺兰县| 泰宁县| 开平市| 拉孜县| 唐山市| 金华市| 开阳县| 株洲县| 资中县| 木兰县| 开封市| 郓城县| 遂平县| 炎陵县| 柏乡县| 泸定县| 远安县| 从化市| 延庆县| 治多县| 绥阳县| 乌拉特中旗| 阜南县| 富平县| 洪洞县| 淄博市|