go语言的命令行库
命令行應用通常很小,程序猿們也不喜歡為它編寫注釋。所以一些額外的工作,如解析參數有個合理的庫來幫忙做就好了。
https://github.com/urfave/cli 這個項目因此而生。
安裝:go get github.com/urfave/cli
以下的例子均來自官網:
(例1)
package mainimport ("os""github.com/urfave/cli" )func main() {cli.NewApp().Run(os.Args) }?
(例2)
package mainimport ("fmt""os""github.com/urfave/cli" )func main() {app := cli.NewApp()app.Name = "greet"app.Usage = "fight the loneliness!"app.Action = func(c *cli.Context) error {fmt.Println("Hello friend!")return nil}app.Run(os.Args) }?
(例3)
package mainimport ("fmt""os""github.com/urfave/cli" )func main() {app := cli.NewApp()app.Action = func(c *cli.Context) error {fmt.Printf("Hello %q\n", c.Args().Get(0))return nil }app.Run(os.Args) }?
?
?(例4)
package mainimport ("fmt""os""github.com/urfave/cli" )func main() {app := cli.NewApp()app.Flags = []cli.Flag {cli.StringFlag{Name: "lang",Value: "english",Usage: "language for the greeting",},}app.Action = func(c *cli.Context) error {name := "Nefertiti"if c.NArg() > 0 {name = c.Args().Get(0)}if c.String("lang") == "spanish" {fmt.Println("Hola", name)} else {fmt.Println("Hello", name)}return nil}app.Run(os.Args) }?
還有幾個小例子,情況差不多,請自行閱讀。
?
?
然而,事情到這里并沒有結束。。。
參數的解析還可以從yaml和toml里面獲取,這是兩個什么東東?
經常寫配置文件的會用到ini, xml, json格式;后2個寫起來太虐心,ini語法舒服但結構性缺陷決定它只能寫簡單配置。
因此yaml誕生(2001年)了,阮一峰在幾個月前寫了一篇教程:http://www.ruanyifeng.com/blog/2016/07/yaml.html
yaml不斷發展,此后日益復雜,導致積重難返,github創始人主導了一個新的項目toml:http://mlworks.cn/posts/introduction-to-toml/
從語法簡單性來說:ini > toml > yaml > json > xml
個人認為,沒有必要強上yaml/toml,簡單的用ini,稍復雜的json,很復雜的xml。
總結
- 上一篇: windows环境下的zookeeper
- 下一篇: go get安装第三方包的前提条件和步骤