官网
https://cobra.dev/ A Framework for Modern CLI Apps in Go
安装cobra
go install github.com/spf13/cobra-cli@latest
将cobra下载完成后,GOPATH/bin目录会生成一个cobra可执行程序,通过这个程序我们可以初始化一个cobra代码框架。
初始化一个demo工程
mkdir cobratest && cd cobratest
go mod init cobratest
cobra-cli init
cobra-cli
cobra-cli add test // 添加子命令test,自动生成 cmd/test.go
完整示范
var name string
var age int
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "cobratest",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains`,
Run: func(cmd *cobra.Command, args []string) { // run方法为命令的运行执行方法
fmt.Println("cobratest", args, name, age)
},
}
func Execute() { // 执行入口 见 main.go cmd.Exceute()
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
rootCmd.AddCommand(testCmd) // 添加一个子命令
}
func initConfig() {
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
rootCmd.Flags().IntVarP(&age, "age", "a", 0, "person's age")
}
var testCmd = &cobra.Command{ // 子命令test定义
Use: "test",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("test called")
},
}
go run main.go -a 12 -n ww => cobratest [] ww 12 // 主命令
go run main.go test => test called // 子命令test
文章介绍了如何使用Cobra库在Go中创建命令行界面(CLI)应用。首先通过goinstall安装Cobra,然后在GOPATH/bin目录下生成可执行程序。接着,演示了如何初始化一个名为cobratest的项目,添加子命令test,并定义命令参数如name和age。最后展示了主命令和子命令的运行示例。

520

被折叠的 条评论
为什么被折叠?



