go cobra包
最近看了幾個開源專案,都是基於cobra建立的專案,如果對cobra不瞭解的話,對整個專案的程式碼閱讀難度都相應的要增加。
首先,cobra是什麼?
cobra既是一個用來建立強大的現代CLI命令列的golang庫,也是一個生成程式應用和命令列檔案的程式。
Cobra提供的功能
1、簡易的子命令列模式,如app server、app get等
2、完全相容posix命令列模式
3、支援全域性、區域性、串聯flags
4、使用cobra很容易生成應用程式和命令,使用cobra create和cobra cmdname
5、如果命令輸入有錯誤,將提供只能建議,如app gt,將提示gt不存在,是否是app get
6、自動生成詳細的help資訊,如app help
7、自動識別-h,--help和幫助flag
8、自動生成應用程式在bash下命令自動改完成功能
9、自動生成應用程式的man手冊
10、命令列別名
11、自定義help和usage資訊
12、可選的緊密整合的viper apps
上面的描述稍微有點抽象,下面結合例子講下cobra如何做的。
首先,通過go get下載cobra
go get -v github.com/spf13/cobra/cobra
然後安裝go install。
至此cobra工具安裝完成。
在命令列下執行下cobra命令

看到上述資訊,說明cobra安裝成功。接下來就可以使用cobra了。
假設我們現在要開發一個基於CLI的命令程式,名字的demo。如下圖操作:

建立初始化程式
然後就會在gopath目錄下建立一個cobra_demo目錄。其內部的目錄結構如下:
▾ cobra_demo
▾ cmd/
root.go
main.go
如果此時cobra_demo程式沒有subcommands,那麼cobra生成應用程式的操作就結束了。
功能基本在root.go檔案中,內容如下:
var rootCmd = &cobra.Command{
Use:"demo",
Short:"A brief description of your application",
Long:`A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Run: func(cmd *cobra.Command, args []string) { },
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile !="" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".demo" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".demo")
}
viper.AutomaticEnv()// read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
上述的程式碼是沒有經過任何修改的。可以直接執行下看看。下面將上面的程式碼進行下簡單的修改,將 &cobra.Command{}中註釋了的程式碼放開,修改如下:

增加相應的Show方法:

然後執行如下:

至此,cobra的簡單介紹完了。