iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0
Modern Web

從0開始的golang web server系列 第 6

Day6-啟動戰士 Cli

當要執行編寫好的binary時,一般情況會像這樣:

./web-server

但是當要指定是否開啟debug模式,或是資料來源變動時,就會要直接去改程式,在這種情況下,使用Cli,讓他可以依照你指令參數來啟動成不同模式,會是一個比較好的方式。
或許會有人想說,那我將這些參數也放在config.yaml就好了,不過這邊會有個小問題,通常在本機,config.yaml會放在當前目錄,所以路徑上不會有什麼問題,但是公司環境有可能會希望將設定檔集中管理,這時config.yaml路徑變化了,除非改程式,不然無法讀到設定檔,在這種情況下,有Cli可以帶一些不適合放在config內的參數,會是一個比較好的選擇。

urfave/cli

urfave/cli有許多專案在使用它,像是Drone,Gitea和Gogs等等
他為你程式提供指令與其說明的功能,舉例來說,當你直接下go會出現這樣的說明:

Go is a tool for managing Go source code.

Usage:

	go <command> [arguments]

The commands are:

	bug         start a bug report
	build       compile packages and dependencies
	clean       remove object files and cached files
	doc         show documentation for package or symbol
	env         print Go environment information
	fix         update packages to use new APIs
	fmt         gofmt (reformat) package sources
	generate    generate Go files by processing source
	get         add dependencies to current module and install them
	install     compile and install packages and dependencies
	list        list packages or modules
	mod         module maintenance
	run         compile and run Go program
	test        test packages
	tool        run specified go tool
	version     print Go version
	vet         report likely mistakes in packages

這些就是能用的指令跟這些指令的說明,urfave/cli也是可以做到相同功能。

建立cli app

import (
"github.com/urfave/cli/v2"
)

app := cli.NewApp()
	app.Name = "web-server"
	app.Version = "0.0.1"
	app.Compiled = time.Now()
	app.Usage = "easy web server"
	app.UsageText = "web-server command [command options] [arguments...]"
	app.Commands = []*cli.Command{
		{
			Name:   "start",
			Usage:  "you can select env  ex. ./web-server start -e example.env",
			Action: start,
			Flags: []cli.Flag{
				&cli.StringFlag{
					Name:  "env-file,e",
					Usage: "env address",
				},
			},
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		return
	}

上面是簡易的cli app建立,這邊使用的是v2版本,跟v1沒差多少,可以依自己想用的使用。

  1. 首先透過cli.NewApp()建立新的cliApp 這時可以設定這個程式app的名稱(Name),版本(Version),編譯時間(Compiled)等app敘述。
  2. 在app.Commands內,是一個cli.Command的切片(Slice),就是要這個app支援的指令(command),指令參數(Flags)以及用途(Action)。
  3. 指令參數可以設定他能透過指定的指令帶進來的參數,像是上面這個範例可以用 -e 或 -env-file來指令參數檔的位置,範例如下:
./web-server start -e example.env

example.env就是可以帶進去的參數,反之沒再flag內設定的參數,就算放入指令內,程式內部也無法取出。

  1. 最後以app.Run就可以啟動這個app並支援command。

上一篇
Day5-設定檔套件介紹:Viper
下一篇
Day7-Graceful shutdown
系列文
從0開始的golang web server30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言