Golang如何快速構(gòu)建一個CLI小工具詳解
如何Golang快速構(gòu)建一個CLI小工具
在現(xiàn)實開發(fā)的過程中,大家會發(fā)現(xiàn)很多開源的框架都會有著自己的一個CLI工具庫來幫助開發(fā)者們通過命令行的方式快速的達到某些目的,比如常見的docker 命令。
那么在這篇文章當(dāng)中,主要給大家介紹一個golang的小框架,我們可以借助這個框架來快速搭建一個小的CLI工具
先上效果
我們這邊構(gòu)建了一個叫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是我們自己的一個小工具,用來隨機的從輸入的字符列表中選一個作為結(jié)果:
>> gtools as 學(xué)習(xí) 看電影 還是學(xué)習(xí)
學(xué)習(xí)>> gtools as 學(xué)習(xí) 看電影 還是學(xué)習(xí)
還是學(xué)習(xí)
那么如何實現(xiàn)呢?
在這邊,我們用了一個叫cobra的框架,這個框架被廣泛運用到很多開源的產(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初始化我們的項目
cobra-cli init
執(zhí)行完之后,我們會在本地目錄看到這樣的結(jié)構(gòu)
├── main.go ├── cmd │ └── root.go
main.go就是我們的主入口了,root是我們命令的根命令
main.go
// 只是做了一個執(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)在,我們需要加入一個子命令,如autoSelector, 只需執(zhí)行一下命令即可:
cobra-cli add autoSelector
對應(yīng)的一個叫autoSelector.go的文件就會出現(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`, //詳細描述
Run: func(cmd *cobra.Command, args []string) {
// 在這里加入/調(diào)用你的主要邏輯
}
}
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")
}
實現(xiàn)我們的功能
我們可以創(chuàng)建一個pkg包來存放我們的具體實現(xiàn)邏輯,在cmd中只需要做簡單的調(diào)用即可
import (
"math/rand"
"time"
)
// 簡單實現(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
}
此時我們的代碼工具就基本實現(xiàn)完成了,只需要編譯一下就可以直接使用。編譯運行
go build -o gtools
你就可以得到一個叫gtools的二進制包,直接運行就可以看到我們開頭的效果啦~
代碼倉庫: github.com/819110812/G…
以上就是Golang如何快速構(gòu)建一個CLI小工具詳解的詳細內(nèi)容,更多關(guān)于Golang構(gòu)建CLI小工具的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Centos下搭建golang環(huán)境及vim高亮Go關(guān)鍵字設(shè)置的方法
這篇文章先給大家詳細介紹了在Centos下搭建golang環(huán)境的步驟,大家按照下面的方法就可以自己搭建golang環(huán)境,搭建完成后又給大家介紹了vim高亮Go關(guān)鍵字設(shè)置的方法,文中通過示例代碼介紹的很詳細,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-11-11
Go中使用單調(diào)時鐘獲得準(zhǔn)確的時間間隔問題
這篇文章主要介紹了Go中使用單調(diào)時鐘獲得準(zhǔn)確的時間間隔,在go語言中,沒有直接調(diào)用時鐘的函數(shù),可以通過?time.Now()?獲得帶單調(diào)時鐘的?Time?結(jié)構(gòu)體,并通過Since和Until獲得相對準(zhǔn)確的時間間隔,需要的朋友可以參考下2022-06-06
golang中http請求的context傳遞到異步任務(wù)的坑及解決
這篇文章主要介紹了golang中http請求的context傳遞到異步任務(wù)的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
GoLand 2020.3 正式發(fā)布有不少新功能(支持泛型)
這是 2020 年第 3 個版本,也是最后一個版本,你還將發(fā)現(xiàn)許多新的代碼編輯功能,具體內(nèi)容詳情跟隨小編看看有哪些新特性2020-12-12
深入探究Golang中l(wèi)og標(biāo)準(zhǔn)庫的使用
Go?語言標(biāo)準(zhǔn)庫中的?log?包設(shè)計簡潔明了,易于上手,可以輕松記錄程序運行時的信息、調(diào)試錯誤以及跟蹤代碼執(zhí)行過程中的問題等。本文主要來深入探究?log?包的使用和原理,幫助讀者更好地了解和掌握它2023-05-05

