How to quickly build a CLI widget from Golang
In the process of real-life development, you will find that many open source frameworks have their own CLI tool library to help developers quickly achieve certain goals through command line methods, such as commondocker
Order.
So in this article, we will mainly introduce to you a small golang framework. We can use this framework to quickly build a small CLI tool.
First effect
We have built a namegtools
a widget to accommodate our own usegolang
Some small tools developed
>> 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.
HereautoSeletor
It is a gadget of our own, which is used to randomly select one from the input character list as the result:
>> gtools as Learn to watch movies or learn
study>> gtools as Learn to watch movies or learn
Still learning
So how to achieve it?
Here we used a name calledcobra
The framework is widely used in many open source products, such asdocker-compose
, kubectl
wait.
First, we need to install the corresponding environment:
go get -u /spf13/cobra@latest go install /spf13/cobra-cli@latest
After executing the above two commands, we have the most basic development conditions. Let’s start our development!
Initialize our project with Cobra
cobra-cli init
After execution, we will see this structure in the local directory.
├── ├── cmd │ └──
It's our main entrance.
root
It's the root command of our command
// Just did an operationfunc main() { () }
Define the root command, and some initialization operations
var rootCmd = &{ Use: "gtools", // This is the name of your command 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 *, args []string) { }, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by (). It only needs to happen once to the rootCmd. func Execute() { err := () if err != nil { (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. // ().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.)") // Cobra also supports local flags, which will only run // when this action is called directly. ().BoolP("toggle", "t", false, "Help message for toggle") }
Join our subcommand
Now, we need to add a subcommand, such asautoSelector
, just execute the command:
cobra-cli add autoSelector
The corresponding one is calledThe file will appear in
cmd
Under the directory, and you have prepared a basic command line framework for you
// autoSelectorCmd represents the autoSelector command var autoSelectorCmd = &{ Use: "autoSelector", // name Aliases: []string{"as"}, // Abbreviation of the command line Short: "randomly select string from a list", //Simple description Long: `randomly select string from a list`, //Detailed description Run: func(cmd *, args []string) { // Add/call your main logic here } } func init() { // Register under the root command (autoSelectorCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, .: // ().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, .: // ().BoolP("toggle", "t", false, "Help message for toggle") }
Implement our functions
We can create apkg
Packages to store our specific implementation logic,cmd
Just make a simple call
import ( "math/rand" "time" ) // Simple implementation logicfunc AutoSelect(inputs []string) (selected string, err error) { source := (().UnixNano()) r := (source) randomIndex := (len(inputs)) selected = inputs[randomIndex] return selected, nil }
At this time, our code tool has been basically implemented and can be used directly by just compiling it. Compile and run
go build -o gtools
You can get a callgtools
The binary package can be directly run to see the effect at the beginning~
Code repository:/819110812/G…
The above is the detailed explanation of how Golang quickly builds a CLI widget. For more information about Golang building a CLI widget, please follow my other related articles!