Install the cobra
go get -v github.com/spf13/cobra/cobra
Copy the code
Switch to GOPATH’s SRC directory and create a new folder: Demo
cd $GOPATH/src
mkdir demo
cd demo
Copy the code
The initial 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 Application help Help about any command init Initialize a Cobra Application Flags: -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.Copy the code
You can see that COBRA supports two commands, init and add, where init initializes a COBRA project and add adds a subcommand to the project
Initialize the project:
$.. /.. /bin/cobra init --pkg-name demoCopy the code
After the preceding command is executed, the following files and folders are generated
$├── CMD │ ├─ ├─ class.txt, ├─ class.txt, class.txt, class.txt, class.txtCopy the code
main.go
package main
import "imgctl/cmd"
func main() {
cmd.Execute()
}
Copy the code
cmd/root.go
package cmd import ( "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()) } }Copy the code
If you want to implement a CLI tool without subcommands, then the operation of the COBRA generator ends. Since all cobra commands are implemented through the cobra.mand structure, you need to modify RootCmd in the root.go file:
cmd/root.go
package cmd import ( "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()) } }Copy the code
To this our demo function on the completion of the code, the following compilation run
Dependency resolution
go mod init
go mod vendor
Copy the code
Run the demo
$ go run main.go
Demo is a test appcation for print things
Usage:
demo [flags]
Flags:
-a, --age int person's age
-h, --help help for demo
-n, --name string person's name
Copy the code
Add a command
$.. /.. /bin/cobra add [cmdname] # cmdname.go = cmdname.go /.. ├── ├─ ├─ ├─ └.go ├── └.go ├── └.go ├── └.go ├── └.go ├── ├.go, 4 filesCopy the code
cmd/server.go
package cmd import ( "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" - p - parent $tree. ├ ─ ─ CMD │ ├ ─ ─ the create. Go # serverCmd son ordered │ ├ ─ ─ root. Go │ └ ─ ─ for server go ├ ─ ─ LICENSE └ ─ ─ main. Go 1 directory, 5 filesCopy the code
cmd/create.go
package cmd
import (
"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")
}
Copy the code