網站首頁 編程語言 正文
如何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
的二進制包,直接運行就可以看到我們開頭的效果啦~
原文鏈接:https://juejin.cn/post/7160532478296326174
相關推薦
- 2023-05-24 Django獲取前端數據的實現方式_python
- 2022-07-19 Oracle 集群sysbackup用戶登陸隨機報錯ORA-01017
- 2022-09-30 Go語言編譯原理之源碼調試_Golang
- 2022-05-11 剖析數據庫中重要而又常被曲解的概念
- 2022-12-22 Python?Flask框架實現Proteus仿真Arduino與網頁數據交互_python
- 2022-12-28 golang?gin?監聽rabbitmq隊列無限消費的案例代碼_Golang
- 2022-03-23 Android?Camera2開啟自動曝光功能_Android
- 2022-11-28 Flutter?Widgets之標簽類控件Chip詳解_IOS
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支