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 @   明矾  阅读(190)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-03-16 故障注入之如何给服务器CPU注入高负载
点击右上角即可分享
微信分享提示