1. 程式人生 > 實用技巧 >Go+Cobra快速入門

Go+Cobra快速入門

Cobra介紹

  • 一個用於生成命令列工具的框架(本身也是個命令列工具)
  • 非常簡單,易用
  • k8s/docker/hugo/etcd等...

下載安裝

https://github.com/spf13/cobra

$ go get -u github.com/spf13/cobra
// github.com/spf13/cobra/cobra/main.go 編譯後可以放到 GOPTH/bin/ 就可以直接使用了
// 在程式專案中引用 import "github.com/spf13/cobra" 

初始化專案

/*
Usage:
  cobra init [name] [flags]

Aliases:
  init, initialize, initialise, create

Flags:
  -h, --help              help for init
      --pkg-name string   fully qualified pkg name

Global Flags:
  -a, --author string    author name for copyright attribution (default "YOUR NAME")
      --config string    config file (default is $HOME/.cobra.yaml)
  -l, --license string   name of license for the project
      --viper            use Viper for configuration (default true)
*/

// cobra 是github.com/spf13/cobra/cobra/main.go 編譯後的可執行檔案
// 基本初始化
cobra init --pkg-name xxx

// 修改作者資訊
cobra init --pkg-name xxx --athor xxx2

// 指定license資訊
cobra init --pkg-name xxx -license xxx

命令的基本結構

var rootCmd = &cobra.Command{
	Use:   "clid", 
	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.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	//	Run: func(cmd *cobra.Command, args []string) { },
        //      Alias:[]string,
}
func init() {
	rootCmd.AddCommand(versionCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// versionCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// Use: 與短簡介對應顯示 在啟動時顯示
// Short: 簡介,在命令列後會跟一個短的備註
// Long: 一個長的幫助資訊,會在執行-h幫助的時候顯示
// run: func(cmd *cobra.Command, args []string)  cmd是獲取建立的物件指標可以獲取資訊比如選項 cmd.Flags().Get資料型別("引數名稱"),args 獲取沒有捕獲的引數並以切片返回 與 os.Args類似 ->執行對應use命令會執行對應的run函式  
// 在 init 函式中 rootCmd.AddCommand(versionCmd) rootCmd可以替換其他子命令生成的 cobra.Command 物件 實現巢狀關係

編譯與執行

與Go程式編譯執行一致,無特殊需求

為命令新增一個子命令

cobra add xxx // xxx是子命令
// 建立完成後會在cmd目錄下生成一個xxx.go的檔案

為命令新增一個選項

func init() {
	rootCmd.AddCommand(versionCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// versionCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
        // 新增引數
        // versionCmd.Flags().資料型別P("引數名稱","短的名稱",預設值,"提示資訊")
        // 引數名稱一般是 --引數名稱
        // 短的選項一般是 -短的名稱
        // 已經新增的引數在 run 函式中
	versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

選項的接受和處理

// versionCmd represents the version command
var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. 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) {
		fmt.Println("version called")
		// 獲取引數
		v, err := cmd.Flags().GetString("toggle")
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("v", v)
	},
}

修改預設選項

// 如果需要修改初始化的help選項  cobra/command.go
// 1.全部更改
// func (c *Command) InitDefaultHelpCmd()
// 2.部分修改
// func (c *Command) SetHelpFunc(f func(*Command, []string))/(c *Command) SetHelpCommand(cmd *Command)/(c *Command) SetHelpTemplate(s string)