--pkg-name string fully qualified pkg name -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)
var rootCmd = &cobra.Command{ Use: "hugo", //command,代表命令 Short: "Hugo is a very fast static site generator", //对command的简短介绍 Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, //对command的详细介绍 Run: func(cmd *cobra.Command, args []string) { // 命令实际要做的事情 }, } funcExecute() { //启动 if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of Hugo", Long: `All software has versions. This is Hugo's`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") }, }
使用flag
我们有两种
使用步骤
环境准备
go mod init yourpackage 创建你自己的模块
go get -u github.com/spf13/cobra/cobra 加载依赖
初始化
cobra init ./ -a longtao -l GPL --viper 初始化包(在当前目录初始化cobra,作者是longtao,许可是gpl,并使用viper配置)