Go 的cobra-cli的基本使用

Cobra是一个用于创建功能强大的现代CLI应用程序的库。

Cobra提供了自己的程序,可以创建应用程序并添加任何命令

1、安装

go install github.com/spf13/cobra-cli@latest

安装完成后会在GPPATH的bin目录下生成cobra-cli

2、cobra-cli init

初始化模块

mkdir app
go mod init app

初始化Cobra CLI应用程序

cobra-cli init
--------------------------
[root@iZbp1fpui5cmgd2buwhk5fZ app]# ls -al
total 24
drwxr-xr-x 3 root root 4096 Mar 16 23:05 .
drwxr-xr-x 3 root root 4096 Mar 16 23:04 ..
drwxr-x--x 2 root root 4096 Mar 16 23:05 cmd
-rw-r--r-- 1 root root  176 Mar 16 23:05 go.mod
-rw-r--r-- 1 root root  896 Mar 16 23:05 go.sum
-rw-r--r-- 1 root root    0 Mar 16 23:05 LICENSE
-rw-r--r-- 1 root root  114 Mar 16 23:05 main.go

run一下

[root@iZbp1fpui5cmgd2buwhk5fZ app]# 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.

3、给项目添加命令

cobra-cli add serve
cobra-cli add config
cobra-cli add create -p 'configCmd'

最后一个命令有一个-p 标志。这用于分配 父命令分配给新添加的命令。在本例中,我们希望将 “create”命令到“config”命令。如果未指定,所有命令都有一个默认的rootCmd父命令。

执行完成后新增cmd的如下结构

 

 执行run命令查看效果

go run main.go

 

下一步是编辑cmd中的文件,为app应用程序定制它们

 

posted @ 2023-03-16 23:27  明矾  阅读(148)  评论(0编辑  收藏  举报