如何用Golang快速构建一个CLI小工具
docker 

先上效果

gtoolsgolang
>> 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 学习 看电影 还是学习
还是学习

那么如何实现呢?

cobradocker-composekubectl

首先,我们要安装相应的环境:

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.goroot

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.gocmd
// 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")
}

实现我们的功能

pkgcmd
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