Golang如何快速构建一个CLI小工示例
| 这篇文章主要为大家介绍了Golang如何快速构建一个CLI小工具详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪 |
在现实开发的过程中,大家会发现很多开源的框架都会有着自己的一个CLI工具库来帮助开发者们通过命令行的方式快速的达到某些目的,比如常见的docker 命令。
那么在这篇文章当中,主要给大家介绍一个golang的小框架,我们可以借助这个框架来快速搭建一个小的CLI工具
我们这边构建了一个叫gtools的小工具,用来容纳我们自已用golang开发的一些小的工具
>> gtools
gtools is a CLI application for golang command tools.
Usage:
gtools [command]
Available Commands:
autoSelector randomly select string from a list
completion Generate the autocompletion script for the specified shell
help Help about any command
Flags:
-h, --help help for gtools
-t, --toggle Help message for toggle
Use "gtools [command] --help" for more information about a command.
这边的autoSeletor是我们自己的一个小工具,用来随机的从输入的字符列表中选一个作为结果:
>> gtools as 学习 看电影 还是学习
学习 >> gtools as 学习 看电影 还是学习
还是学习
在这边,我们用了一个叫cobra的框架,这个框架被广泛运用到很多开源的产品当中,比如docker-compose, kubectl等。
首先,我们要安装相应的环境:
go get -u github.com/spf13/cobra@latest
go install github.com/spf13/cobra-cli@latest
在执行完上面两条命令后我们就具备最基本的开发条件了,接下来开始我们的开发吧!
使用Cobra初始化我们的项目
cobra-cli init
执行完之后,我们会在本地目录看到这样的结构
├── main.go
├── cmd
│ └── root.go
main.go就是我们的主入口了,root是我们命令的根命令
main.go
// 只是做了一个执行的操作
func main() {
cmd.Execute()
}
Root.go 定义了根命令,还有一些初始化的操作
var rootCmd = &cobra.Command{
Use: "gtools", // 这是你的命令的名字
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/.main.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")
}
加入我们的子命令
现在,我们需要加入一个子命令,如autoSelector, 只需执行一下命令即可:
cobra-cli add autoSelector
对应的一个叫autoSelector.go的文件就会出现在cmd目录底下,并且已经为你准备了基本的命令行框架
// autoSelectorCmd represents the autoSelector command
var autoSelectorCmd = &cobra.Command{
Use: "autoSelector", // 名字
Aliases: []string{"as"}, // 命令行的简写
Short: "randomly select string from a list", //简单的描述
Long: `randomly select string from a list`, //详细描述
Run: func(cmd *cobra.Command, args []string) {
// 在这里加入/调用你的主要逻辑
}
}
func init() {
// 注册到根命令下
rootCmd.AddCommand(autoSelectorCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// autoSelectorCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// autoSelectorCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
实现我们的功能
我们可以创建一个pkg包来存放我们的具体实现逻辑,在cmd中只需要做简单的调用即可
import (
"math/rand"
"time"
)
// 简单实现逻辑
func AutoSelect(inputs []string) (selected string, err error) {
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
randomIndex := r.Intn(len(inputs))
selected = inputs[randomIndex]
return selected, nil
}
此时我们的代码工具就基本实现完成了,只需要编译一下就可以直接使用。编译运行
go build -o gtools
你就可以得到一个叫gtools的二进制包,直接运行就可以看到我们开头的效果啦~
代码仓库: github.com/819110812/G…
原文来自:https://www.jb51.net/article/266390.htm
本文地址:https://www.linuxprobe.com/gtools-golang-linuix.html
Linux命令大全:https://www.linuxcool.com/
Linux系统大全:https://www.linuxdown.com/
红帽认证RHCE考试心得:https://www.rhce.net/
Golang如何快速构建一个CLI小工示例的更多相关文章
- 快速构建一个vue项目
首先介绍一下命令行构建一个vue项目步骤: 1.下载安装node.js(直接运行安装包根据步骤安装完),打开命令行输入:node -v ,出现版本号即安装成功. 2.命令行界面输入:cnpm inst ...
- 【jQuery插件】用jQuery Masonry快速构建一个pinterest网站布局(转)
[jQuery插件]用jQuery Masonry快速构建一个pinterest网站布局 时间:2011年03月21日作者:愚人码头查看次数:29,744 views评论次数:25条评论 前段时间领导 ...
- springboot:快速构建一个springboot项目
前言: springboot作为springcloud的基础,springboot的热度一直很高,所以就有了这个springboot系列,花些时间来了解和学习为自己做技术储备,以备不时之需[手动滑稽] ...
- 快速构建一个简单的单页vue应用
技术栈 vue-cli webpack vux,vux-loader less,less-loader vue-jsonp vue-scroller ES6 vue-cli:一个vue脚手架工具,利用 ...
- 快速构建一个 Springboot
快速构建一个 Springboot 官网:http://projects.spring.io/spring-boot/ Spring Boot可以轻松创建可以“运行”的独立的,生产级的基于Spring ...
- [开源]快速构建一个WebApi项目
项目代码:MasterChief.DotNet.ProjectTemplate.WebApi 示例代码:https://github.com/YanZhiwei/MasterChief.Project ...
- 使用 typescript 快速开发一个 cli
cli 的全称 command-line interface(命令行界面),也就是前端同学常用的脚手架,比如 yo.vue cli.react cli 等. cli 可以方便我们快速创建项目,下图是引 ...
- 看了这一张GIF图你就明白什么回事了,必看的经典!--快速构建一个请假流程
下面介绍一下FSBPM构建一个请假单流程 1.数据模型的构建 输入业务中需要的数据项即可,比如[申请人,开始时间,结束时间,请假天数,请假理由,附件上传..........] 2.自定义流程 审批节点 ...
- 快速构建一个使用axios的vue应用程序(转)
英文原文:https://www.sitepoint.com/fetching-data-third-party-api-vue-axios/ 译文:https://segmentfault.com/ ...
- 快速构建一个springboot项目(一)
前言: springcloud是新一代的微服务框架而springboot作为springcloud的基础,很有必要对springboot深入学习一下. springboot能做什么? (1)spri ...
随机推荐
- 网络爬虫之requests模块,自动办公领域之openpyx模块
一.第三方模块的下载与使用 第三方模块:别人写的模块,一般情况下功能都特别强大 我们如果想使用第三方模块,第一次必须先下载,后面才可以反复使用(等同于内置模块) 下载第三方模块的方式 1. pi ...
- PHP7.2 装mongodb 遇到的坑,完美解决!
公司要做QA安全测试,组长就丢了一个源码包给我,什么资料都无. 系统是个Laravel框架,源码都是从线上git下来.然后看了本地composer.json 没有生成vendor 第一步安装 comp ...
- Kubernetes环境鉴权与自动发现
概览文章中提到了k8s的鉴权模式,简单回顾下: RBAC: Role-based access control 是基于角色的访问控制 ABAC: Atrribute-based access cont ...
- Git使用记录 - 持续更新
本地生成 sshkey 打开git命令工具 cd ~/.ssh ssh-keygen -t rsa -C "实际的eamil地址" ··· // 一路回车,出现以下则说明成功 Yo ...
- TensorRT基础笔记
一,概述 TensorRT 是 NVIDIA 官方推出的基于 CUDA 和 cudnn 的高性能深度学习推理加速引擎,能够使深度学习模型在 GPU 上进行低延迟.高吞吐量的部署.采用 C++ 开发,并 ...
- CVE-2022-32532 Apache Shiro 身份认证绕过
漏洞名称 CVE-2022-32532 Apache Shiro 身份认证绕过 利用条件 Apache Shiro < 1.9.1 漏洞原理 使用RegexRequestMatcher进行权限配 ...
- [cocos2d-x]用getContentSize()返回的值用CCLOG打印必须用%f
今天写代码,又遇到了一个bug,开始还以为是我自己哪写错了,没想到竟然在这里出错? 而width和height的类型是float类型,为什么必须用%d打印?接着我查看了一下源码: 如果没理解错的话,C ...
- SwiftUI(二)
也许很多人看完一会有一个疑问,为什么UIHostingController我这里报错呢 看到这里大家心中的疑问也就解开了 接下来给大家说下@State的作用 通过@State swiftUI实 ...
- MySQL优化四,高性能优化
一,查询优化器 这个部分的整个过程是由MySQL的存储引擎来做的,优化器就会根据存储引擎来使用原来的开销, 优化后的开销,哪个更好一点? 1.如果是查询语句(select语句),首先会查询缓存是否已有 ...
- Ubuntu snap 下载慢
解决方法 sudo apt-get install snapd sudo snap install snap-store sudo snap install snap-store-proxy sudo ...