Why use the command line
In large projects, there is no data upgrade, if the use of Web services, a lack of security, and a large amount of data will also be out of time. This is the appropriate way to use the command line.
MVC in the command line
Web projects generally take the MVC pattern, do you have a command line?
Command (command) and flag (parameters) are available for the Golang, but not powerful enough, we use third party packages Cobra
Use of Cobra
You can refer to the official documentation for specific usage, I will not elaborate.
Calmness
According to the official structure, do not realize automatic registration, each time adding new commands or folders bad management, need to change the code. After some thought, I found that I could use the init mechanism of Golang to achieve my goal.
The directory structure is as follows:
Run effect
Where Rootcmd.go initialize the root command rootCmd
, while encapsulating two functions, one is the addition of subcommands, one is executed.
package rootcmdimport ( "fmt" "github.com/spf13/cobra")var rootCmd = &cobra.Command{ Use: "cli", Run: func(cmd *cobra.Command, args []string) { fmt.Println("OK") },}//封装了两个函数func AddCommand(cmd *cobra.Command) { rootCmd.AddCommand(cmd)}func Execute() error { return rootCmd.Execute()}
For subcommands, I can import the package where Rootcmd is located, and then in the INIT function, call Rootcmd. AddCommand
Like Updatecmd.go.
package updateimport ( "github.com/spf13/cobra" "fmt" "github.com/dwdcth/cli_sample/rootcmd")// 注册命令func init() { rootcmd.AddCommand(userCmd)}var userCmd = &cobra.Command{ Short: "user", Use: "user ", Run: func(cmd *cobra.Command, args []string) { fmt.Println("run user update command") },}
For main package, use "_", Import sub-command folder, and Rootcmd, and call Rootcmd. Execute ().
When you add a new command without adding a new package, you do not need to change the cli.go to achieve the purpose of autoenrollment.
package mainimport ( "fmt" "os" "github.com/dwdcth/cli_sample/rootcmd" _"github.com/dwdcth/cli_sample/task" _"github.com/dwdcth/cli_sample/update")func main() { if err := rootcmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) }}
The complete code is here