詳細信息參考:https://www.jb51.net/article/202380.htm
package main import ( "github.com/urfave/cli" "os" "log" "fmt" ) func main() { //實例化一個命令行程序 oApp := cli.NewApp() //程序名稱 oApp.Name = "GoTool" //程序的用途描述 oApp.Usage = "To save the world" //程序的版本號 oApp.Version = "1.0.0" //該程序執行的代碼 oApp.Action = func(c *cli.Context) error { fmt.Println("Test") return nil } //啟動 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 */ }
我們看到運行 go run main.go help 之后會輸出一些幫助信息,說明你的程序已經成功成為一個命令行程序,接着使用命令 go run main.go 運行這個程序,結果是打印了Test信息,所以這個程序實際運行的函數由oApp.Action來控制,你后面的代碼應該都在這個函數的內部去實現。
package main import ( "fmt" "log" "os" "github.com/urfave/cli" ) func main() { //實例化一個命令行程序 oApp := cli.NewApp() //程序名稱 oApp.Name = "GoTool" //程序的用途描述 oApp.Usage = "To save the world" //程序的版本號 oApp.Version = "1.0.0" //預置變量 var host string var debug bool //設置啟動參數 oApp.Flags = []cli.Flag{ //參數類型string,int,bool cli.StringFlag{ Name: "host", //參數名字 Value: "127.0.0.1", //參數默認值 Usage: "Server Address", //參數功能描述 Destination: &host, //接收值的變量 }, cli.IntFlag{ Name: "port,p", Value: 8888, Usage: "Server port", }, cli.BoolFlag{ Name: "debug", Usage: "debug mode", Destination: &debug, }, } //該程序執行的代碼 oApp.Action = func(c *cli.Context) error { fmt.Printf("host=%v \n", host) fmt.Printf("port=%v \n", c.Int("port")) //不使用變量接收,直接解析 fmt.Printf("debug=%v \n", debug) return nil } //啟動 if err := oApp.Run(os.Args); err != nil { log.Fatal(err) } }
運行:
# go run cli.go --port 7777 host=127.0.0.1 port=7777 debug=false
執行 go run main.go --port 7777 之后,可以看到輸出了設定的7777端口而非默認的8888端口,而服務器地址(host)和調試模式(debug)都輸出了默認的數值。
如果第三方人員第一次使用你的程序也可以通過help命令看到可以設定的參數都有哪些,非常的人性化。