日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

命令行工具cobra的使用

發布時間:2025/3/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 命令行工具cobra的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

安裝cobra

go get -v github.com/spf13/cobra/cobra

切換到GOPATH的src目錄下并創建一個新文件夾:demo

cd $GOPATH/src mkdir demo cd demo

初始cobra

$ ../../bin/cobra 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.Usage:cobra [command]Available Commands:add Add a command to a Cobra Applicationhelp Help about any commandinit Initialize a Cobra ApplicationFlags:-a, --author string author name for copyright attribution (default "YOUR NAME")--config string config file (default is $HOME/.cobra.yaml)-h, --help help for cobra-l, --license string name of license for the project--viper use Viper for configuration (default true)Use "cobra [command] --help" for more information about a command.

可以看到cobra支持兩個命令,一個是init, 一個是add,其中init是初始化一個cobra工程,add是給工程中添加一個子命令

初始化該項目:

$ ../../bin/cobra init --pkg-name demo

執行完上述命令后會生成如下幾個文件及文件夾

$ tree . ├── cmd │ └── root.go ├── LICENSE └── main.go1 directory, 3 files

main.go

package mainimport "imgctl/cmd"func main() {cmd.Execute() }

cmd/root.go

package cmdimport ("fmt""os""github.com/spf13/cobra"homedir "github.com/mitchellh/go-homedir""github.com/spf13/viper")var cfgFile string// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{Use: "cobra-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.`,// Uncomment the following line if your bare application// has an action associated with it:// Run: func(cmd *cobra.Command, args []string) { }, }// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() {if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)} }func init() {cobra.OnInitialize(initConfig)// Here you will define your flags and configuration settings.// Cobra supports persistent flags, which, if defined here,// will be global for your application.rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-demo.yaml)")// Cobra also supports local flags, which will only run// when this action is called directly.rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }// 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 ".cobra-demo" (without extension).viper.AddConfigPath(home)viper.SetConfigName(".cobra-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())} }

如果要實現一個沒有子命令的CLI工具,那么由cobra生成程序的操作就結束了,由于cobra的所有命令都是通過cobra.Command這個結構體實現的,因此這里就需要對root.go文件中的RootCmd進行修改:

cmd/root.go

package cmdimport ("fmt""os""github.com/spf13/cobra"homedir "github.com/mitchellh/go-homedir""github.com/spf13/viper")var cfgFile string var name string var age int// rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{Use: "demo",Short: "A test demo",Long: `Demo is a test appcation for print things`,// Uncomment the following line if your bare application// has an action associated with it:Run: func(cmd *cobra.Command, args []string) {if len(name) == 0 {cmd.Help()return}fmt.Println(name, age)}, }// Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() {if err := rootCmd.Execute(); err != nil {fmt.Println(err)os.Exit(1)} }func init() {cobra.OnInitialize(initConfig)// Here you will define your flags and configuration settings.// Cobra supports persistent flags, which, if defined here,// will be global for your application.rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-demo.yaml)")rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")rootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")// Cobra also supports local flags, which will only run// when this action is called directly.rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }// 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 ".cobra-demo" (without extension).viper.AddConfigPath(home)viper.SetConfigName(".cobra-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())} }

到此我們的demo功能就編碼完成了,下面編譯運行

解決依賴

go mod init go mod vendor

運行demo

$ go run main.go Demo is a test appcation for print thingsUsage:demo [flags]Flags:-a, --age int person's age-h, --help help for demo-n, --name string person's name

添加命令

$ ../../bin/cobra add [cmdname] # 執行后會在cmd目錄下生成一個cmdname.go的文件,具體處理函數在該文件中編輯 $ ../../bin/cobra add server $ tree . ├── cmd │ ├── root.go │ └── server.go # rootCmd的子命令 ├── LICENSE └── main.go1 directory, 4 files

cmd/server.go

package cmdimport ("fmt""github.com/spf13/cobra" )// serverCmd represents the server command var serverCmd = &cobra.Command{Use: "server",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("server called")}, }func init() {rootCmd.AddCommand(serverCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// serverCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }$ ../../bin/cobra add create -p "serverCmd" #執行該命令是為server子命令再創建一級子命令,-p --parent $ tree . ├── cmd │ ├── create.go # serverCmd的子命令 │ ├── root.go │ └── server.go ├── LICENSE └── main.go1 directory, 5 files

cmd/create.go

package cmdimport ("fmt""github.com/spf13/cobra" )// creatCmd represents the creat command var creatCmd = &cobra.Command{Use: "creat",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("creat called")}, }func init() {serverCmd.AddCommand(creatCmd)// Here you will define your flags and configuration settings.// Cobra supports Persistent Flags which will work for this command// and all subcommands, e.g.:// creatCmd.PersistentFlags().String("foo", "", "A help for foo")// Cobra supports local flags which will only run when this command// is called directly, e.g.:// creatCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") }

總結

以上是生活随笔為你收集整理的命令行工具cobra的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。