社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
cobra是golang里面一个cli库,地址 https://github.com/spf13/cobra
功能包括:
自定义help和usage信息
一个简单的练习
首先安装cobra go get -v github.com/spf13/cobra/cobra
使用cobra在src目录生成一个简单的工程 cobra init demo
生成的工程结构如图
cmd/root.go
package cmd
import (
"demo/imp"
"fmt"
"os"
"github.com/spf13/cobra"
)
var name string
var age int
var rootCmd = &cobra.Command{
Use: "demo",
Short: "this is a test",
Long: `this is a test long `,
Run: func(cmd *cobra.Command, args []string) {
if len(name) == 0 {
cmd.Help()
return
}
imp.Show(name, age)
},
}
// 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() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
rootCmd.Flags().StringVarP(&name, "name", "n", "", "person's name")
rootCmd.Flags().IntVarP(&age, "age", "a", 0, "Person's age")
}
cmd/imp/imp.go
package imp
import (
"fmt"
)
func Show(name string, age int) {
fmt.Printf("My Name is %s,My age is %dn", name, age)
}
使用go build .
编译后运行如下
Administrator@P-V-12 MINGW64 /e/goproject/src/demo
$ ./demo.exe --name tom --age 25
My Name is tom,My age is 25
Administrator@P-V-12 MINGW64 /e/goproject/src/demo
$ ./demo.exe -n tom -a 25
My Name is tom,My age is 25
添加子命令
使用cobra add test
添加子命令test,在cmd目录下生成test.go
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// testCmd represents the test command
var testCmd = &cobra.Command{
Use: "test",
Short: "id test",
Long: `this is a id test`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("test called")
},
}
func init() {
rootCmd.AddCommand(testCmd)
}
运行效果如下
Administrator@P-V-12 MINGW64 /e/goproject/src/demo
$ ./demo.exe test
test called
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!