1. 程式人生 > >Go語言學習筆記(十七)之命令列引數

Go語言學習筆記(十七)之命令列引數

24.1命令列引數

os.Args命令列引數的切片

  1: func main() {
  2: 	name := "Alice"
  3: 	fmt.Println("Good Morning", name)
  4: 	// 說明使用者傳入了引數
  5: 	if len(os.Args) > 1 {
  6: 		for index, v := range os.Args{
  7: 			if index != 0 { // index=0的命令列引數是檔案路徑
  8: 				// 列印每個引數
  9: 				fmt.Printf("args[%d]=%v\n", index, v)
 10: 			}
 11: 		}
 12: 	}
 13: }

使用flag包獲取命令列引數

  1: var recusive bool
  2: var test string
  3: var level int
  4: 
  5: func init() {
  6: 	flag.BoolVar(&recusive, "r", false, "recusive xxx")
  7: 	flag.StringVar(&test, "t", "defalut string", "string option")
  8: 	flag.IntVar(&level, "l", 1, "level of xxxx")
  9: 	flag.Parse()
 10: }
 11: 
 12: func main()  {
 13: 	fmt.Printf("recusive:%v\n", recusive)
 14: 	fmt.Printf("test:%v\n", test)
 15: 	fmt.Printf("level:%v\n", level)
 16: }

終端執行

  1: test.exe -r -t hello -l 8888

執行結果

  1: recusive:true
  2: test:hello
  3: level:8888

24.2 cli框架

首先使用命令安裝cli,go get github.com/urfave/cil

1.基本使用

Action裡面的就是業務邏輯,自動封裝了-help -version等方法

  1: package main
  2: import (
  3: 	"fmt"
  4: 	"github.com/urfave/cli"
  5: 	"log"
  6: 	"os"
  7: )
  8: func main() {
  9: 	app := cli.NewApp()
 10: 	app.Name = "boom"
 11: 	app.Usage = "make an explosive entrance"
 12: 	app.Action = func(c *cli.Context) error {
 13: 		fmt.Println("boom! I say!")
 14: 		return nil
 15: 	}
 16: 
 17: 	err := app.Run(os.Args)
 18: 	if err != nil {
 19: 		log.Fatal(err)
 20: 	}
 21: }

2.處理args第一個引數

比如輸入引數alex,返回 hello "alex!"

  1: package main
  2: 
  3: import (
  4: 	"fmt"
  5: 	"github.com/urfave/cli"
  6: 	"log"
  7: 	"os"
  8: )
  9: 
 10: func main() {
 11: 	app := cli.NewApp()
 12: 
 13: 	app.Action = func(c *cli.Context) error {
 14: 		//獲取第一個引數
 15: 		fmt.Printf("Hello %q", c.Args().Get(0))
 16: 		return nil
 17: 	}
 18: 
 19: 	err := app.Run(os.Args)
 20: 	if err != nil {
 21: 		log.Fatal(err)
 22: 	}
 23: }

3.Flag

  1: package main
  2: 
  3: import (
  4: 	"fmt"
  5: 	"github.com/urfave/cli"
  6: 	"log"
  7: 	"os"
  8: )
  9: 
 10: func main() {
 11: 	app := cli.NewApp()
 12: 
 13: 	app.Flags = []cli.Flag{
 14: 		cli.StringFlag{
 15: 			Name:  "lang",
 16: 			Value: "english",
 17: 			Usage: "language for the greeting",
 18: 		},
 19: 	}
 20: 
 21: 	app.Action = func(c *cli.Context) error {
 22: 		name := "Nefertiti"
 23: 		if c.NArg() > 0 {
 24: 			name = c.Args().Get(0)
 25: 		}
 26: 		if c.String("lang") == "spanish" {
 27: 			fmt.Println("Hola", name)
 28: 		} else {
 29: 			fmt.Println("Hello", name)
 30: 		}
 31: 		return nil
 32: 	}
 33: 
 34: 	err := app.Run(os.Args)
 35: 	if err != nil {
 36: 		log.Fatal(err)
 37: 	}
 38: }
  1: 輸入引數alex -lang spanish
  2: 結果 Hello alex

4.關於commond和subcommand

通過定義這些,我們能實現類似可執行程式 命令 子命令的操作,比如 App.go add 123 控制檯輸出 added task:  123

  1: package main
  2: 
  3: import (
  4: 	"fmt"
  5: 	"log"
  6: 	"os"
  7: 	"github.com/urfave/cli"
  8: )
  9: 
 10: func main() {
 11: 	app := cli.NewApp()
 12: 
 13: 	app.Commands = []cli.Command{
 14: 		{
 15: 			Name:    "add",
 16: 			Aliases: []string{"a"},
 17: 			Usage:   "add a task to the list",
 18: 			Action: func(c *cli.Context) error {
 19: 				fmt.Println("added task: ", c.Args().First())
 20: 				return nil
 21: 			},
 22: 		},
 23: 		{
 24: 			Name:    "complete",
 25: 			Aliases: []string{"c"},
 26: 			Usage:   "complete a task on the list",
 27: 			Action: func(c *cli.Context) error {
 28: 				fmt.Println("completed task: ", c.Args().First())
 29: 				return nil
 30: 			},
 31: 		},
 32: 		{
 33: 			Name:    "template",
 34: 			Aliases: []string{"t"},
 35: 			Usage:   "options for task templates",
 36: 			Subcommands: []cli.Command{
 37: 				{
 38: 					Name:  "add",
 39: 					Usage: "add a new template",
 40: 					Action: func(c *cli.Context) error {
 41: 						fmt.Println("new task template: ", c.Args().First())
 42: 						return nil
 43: 					},
 44: 				},
 45: 				{
 46: 					Name:  "remove",
 47: 					Usage: "remove an existing template",
 48: 					Action: func(c *cli.Context) error {
 49: 						fmt.Println("removed task template: ", c.Args().First())
 50: 						return nil
 51: 					},
 52: 				},
 53: 			},
 54: 		},
 55: 	}
 56: 
 57: 	err := app.Run(os.Args)
 58: 	if err != nil {
 59: 		log.Fatal(err)
 60: 	}
 61: }
 62: 

類似MYSQL,FTP,TELNET等工具,很多控制檯程式,都是進入類似一個自己的執行介面,這樣其實CLI本身因為並沒有中斷,可以儲存先前操作的資訊。
所以,我們往往只需要使用者登陸一次,就可以繼續執行上傳下載查詢通訊等等的後續操作。

程式碼省略。