前言
看了许多cobra的安装与使用,许多博客是几年以前的,并不适用(cobra的git仓库更新了),于是决定还是自己写一篇博客给后面的人参考参考
写博客的时间:2022-07-22
使用goland进行配置的
一、go env的配置
博主使用的是目前最新版本的go : go1.18.4
,
镜像源的设置 – GOPROXY
在命令行模式下使用命令
go env -w GOPROXY=https://goproxy.cn,direct
修改完即可
二、cobra的安装与cobra-cli的安装
有小伙伴肯定会好奇,为啥要安装两个,因为我看其他人的博客时发现,他们的教程都是只要安装一个就可以,但是我在实践过程中发现根本行不通,使用cobra init
是总会报错,于是我进cobra的git仓库看了一下,原来是因为cobra的仓库更新了,要安装cobra-cli 才能使用命令cobra-cli init
初始化文件夹
1.cobra的安装
cobra的安装与其他库的安装一样,只需要使用命令
go get -u github.com/spf13/cobra@latest
进行安装即可。
1.测试是否安装成功
- 新建一个项目,项目名为CLI,(项目名可以修改,按自己的习惯来,博主建立的是CLI)
- 在项目文件夹中新建一个名为cmd的文件夹
- 在cmd文件夹中新建一个名为root的go文件
文件中的内容为
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"os"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "CLI",
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.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.CLI.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
- 新建一个名为main的go文件(由于博主的工程名为CLI 所以import 中的内容为CLI/cmd,可根据自己的项目名修改CLI为自己的项目名)
文件内容为
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package main
import "CLI/cmd"
func main() {
cmd.Execute()
}
- 在goland的终端中使用
go mod tidy
,添加需要用到但go.mod中查不到的模块。(这一步只要你导入cobra不报错就证明你安装包成功)
- 运行主函数,输出应该为
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.
2.cobra-cli的安装
使用命令go install github.com/spf13/cobra-cli@latest
进行安装
cobra-cli的使用
- 新建一个项目,项目名自由发挥,我建立的是test
- 使用命令
cobra-cli init
,进行初始化,初始化后的项目结构应为
demo
├── cmd
│ └── root.go
├── go.mod
│ └── go.sum
├── LICENSE
└── main.go
- cobra-cli 的其他命令请进cobra-cli仓库自行查看
地址为:https://github.com/spf13/cobra-cli/blob/main/README.md