1.创建gomod文件
2.设置gomod,通过gomod拉取cobra
GOPROXY=https://goproxy.cn,direct, https://github.com;GO111MODULE=on
4. 控制台拉取包
go get -v github.com/spf13/cobra
go install github.com/spf13/cobra/cobra
5.创建demo,进入到bin目录下执行cobra init --pkg-name demo
出现如下目录:
6.运行
main.go中的import中demo需要修改为module内容,否则会编译失败
执行
go run main.go
可以看到
E:\workspace\cobraDemo>go run main.go
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.
1.添加子命令
使用cobra add test
添加子命令test,在cmd目录下生成test.go
E:\workspace\cobraDemo>cobra add test
test created at E:\workspace\cobraDemo
验证
go run main.go test
打印
E:\workspace\cobraDemo>go run main.go test
test called
2. root修改应用示例
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"os"
"github.com/spf13/viper"
)
var cfgFile string
//增加name参数
var name string
var rootCmd = &cobra.Command{
Use: "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.`,
Run: func(cmd *cobra.Command, args []string) {
//赋值
fmt.Println(name)
},
}
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.demo.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
//参数给变量赋值
rootCmd.PersistentFlags().StringVar(&name, "name", "", "name demo")
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".demo")
}
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
}
go run main.go -h
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.
Usage:
demo [flags]
demo [command]
Available Commands:
completion generate the autocompletion script for the specified shell
help Help about any command
test A brief description of your command
Flags:
--config string config file (default is $HOME/.demo.yaml)
-h, --help help for demo
--name string name demo
-t, --toggle Help message for toggle
Use "demo [command] --help" for more information about a command.
执行,输出:
E:\workspace\cobraDemo>go run main.go --name zhangsan
zhangsan