This is a creation in Article, where the information may have evolved or changed.
+++
Title= "Golang Advanced (ii)--COBRA more practical command line"
Date= "2017-10-11"
tags=["Golang", "Glide", "Docker"]
categories=["Resource Management"]
Description= "Golang itself with the command-line package, a variety of case, a code neat people looking at the big head"
+++
Cobra is a very good command-line package, and Docker,hugo are using
Base command
First create a base command
package cmdimport ( "github.com/spf13/cobra")var RootCmd = &cobra.Command{ "gonne", func(cmd *cobra.Command, args []string) { println("gonne is my ai friend") },}
Using commands
Invoke the command in the main method, yes, it's that simple.
package mainimport ( "fmt" "os" "lastsweetop.com/cmd")func main() { ifnil { fmt.Println(err) os.Exit(1) }}
At the command-line input gonne
, the methods in the base command are executed Run
appletekiMacBook-Pro:src apple$ gonnegonne is my ai friend
Sub-command
Adding subcommands to the base command is also fairly straightforward, eliminating the need to write any code in the base command and the main method, just create a new go file, and the multiple subcommands are independent of each other, how elegant the code is, and say goodbye to the various case
package cmdimport"github.com/spf13/cobra"func init() { RootCmd.AddCommand(versionCmd)}var versionCmd = &cobra.Command{ Use: "version", "Print the version number of Gonne", func(cmd *cobra.Command, args []string) { println("gonne version is 0.0.1") },}
The effect is as follows:
0.0.1
Other
There is also a question about the parameters, we next and how to do a background process together to speak