網(wǎng)站首頁 編程語言 正文
如何Golang快速構(gòu)建一個(gè)CLI小工具
在現(xiàn)實(shí)開發(fā)的過程中,大家會(huì)發(fā)現(xiàn)很多開源的框架都會(huì)有著自己的一個(gè)CLI工具庫來幫助開發(fā)者們通過命令行的方式快速的達(dá)到某些目的,比如常見的docker
命令。
那么在這篇文章當(dāng)中,主要給大家介紹一個(gè)golang的小框架,我們可以借助這個(gè)框架來快速搭建一個(gè)小的CLI工具
先上效果
我們這邊構(gòu)建了一個(gè)叫gtools
的小工具,用來容納我們自已用golang
開發(fā)的一些小的工具
>> 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
是我們自己的一個(gè)小工具,用來隨機(jī)的從輸入的字符列表中選一個(gè)作為結(jié)果:
>> gtools as 學(xué)習(xí) 看電影 還是學(xué)習(xí)
學(xué)習(xí)>> gtools as 學(xué)習(xí) 看電影 還是學(xué)習(xí)
還是學(xué)習(xí)
那么如何實(shí)現(xiàn)呢?
在這邊,我們用了一個(gè)叫cobra
的框架,這個(gè)框架被廣泛運(yùn)用到很多開源的產(chǎn)品當(dāng)中,比如docker-compose
, kubectl
等。
首先,我們要安裝相應(yīng)的環(huán)境:
go get -u github.com/spf13/cobra@latest go install github.com/spf13/cobra-cli@latest
在執(zhí)行完上面兩條命令后我們就具備最基本的開發(fā)條件了,接下來開始我們的開發(fā)吧!
使用Cobra初始化我們的項(xiàng)目
cobra-cli init
執(zhí)行完之后,我們會(huì)在本地目錄看到這樣的結(jié)構(gòu)
├── main.go ├── cmd │ └── root.go
main.go
就是我們的主入口了,root
是我們命令的根命令
main.go
// 只是做了一個(gè)執(zhí)行的操作 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") }
加入我們的子命令
現(xiàn)在,我們需要加入一個(gè)子命令,如autoSelector
, 只需執(zhí)行一下命令即可:
cobra-cli add autoSelector
對(duì)應(yīng)的一個(gè)叫autoSelector.go
的文件就會(huì)出現(xiàn)在cmd
目錄底下,并且已經(jīng)為你準(zhǔn)備了基本的命令行框架
// 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`, //詳細(xì)描述 Run: func(cmd *cobra.Command, args []string) { // 在這里加入/調(diào)用你的主要邏輯 } } func init() { // 注冊(cè)到根命令下 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") }
實(shí)現(xiàn)我們的功能
我們可以創(chuàng)建一個(gè)pkg
包來存放我們的具體實(shí)現(xiàn)邏輯,在cmd
中只需要做簡單的調(diào)用即可
import ( "math/rand" "time" ) // 簡單實(shí)現(xiàn)邏輯 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 }
此時(shí)我們的代碼工具就基本實(shí)現(xiàn)完成了,只需要編譯一下就可以直接使用。編譯運(yùn)行
go build -o gtools
你就可以得到一個(gè)叫gtools
的二進(jìn)制包,直接運(yùn)行就可以看到我們開頭的效果啦~
原文鏈接:https://juejin.cn/post/7160532478296326174
相關(guān)推薦
- 2022-06-22 C語言進(jìn)階教程之函數(shù)指針詳解_C 語言
- 2022-07-12 Linux系統(tǒng)下的時(shí)區(qū)配置管理
- 2023-03-02 C++版本基于ros將文件夾中的圖像轉(zhuǎn)換為bag包_C 語言
- 2023-03-29 goland遠(yuǎn)程調(diào)試k8s上容器的實(shí)現(xiàn)_Golang
- 2022-09-03 Python流程控制if條件選擇與for循環(huán)_python
- 2022-07-27 P標(biāo)簽如何取消上下間隔
- 2022-10-31 解讀Python腳本的常見參數(shù)獲取和處理方式_python
- 2022-09-19 Python使用read_csv讀數(shù)據(jù)遇到分隔符問題的2種解決方式_python
- 欄目分類
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支