golang cobra命令行工具代码示例

version是一个子命令,用于输出版本号

代码

package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

// 创建一个命令
var rootCmd = &cobra.Command{
    
    
	Use:   "example",
	Short: "An example CLI application",
	Long:  "A detailed description of the CLI application",
	Run: func(cmd *cobra.Command, args []string) {
    
    
		fmt.Println("Hello, World!")
	},
}

// 添加子命令
func init() {
    
    
	rootCmd.AddCommand(versionCmd)
}

// 创建一个子命令
var versionCmd = &cobra.Command{
    
    
	Use:   "version",
	Short: "Print the version number of the CLI application",
	Long:  "All software has versions. This is CLI application's",
	Run: func(cmd *cobra.Command, args []string) {
    
    
		fmt.Println("1.0.0")
	},
}

func main() {
    
    
	if err := rootCmd.Execute(); err != nil {
    
    
		fmt.Println(err)
		os.Exit(1)
	}
}

测试

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/a772304419/article/details/129734850