【Go】通过Cobra构建命令行程序

Cobra是当前Go语言中最流行的命令行程序构建库,在Docker、K8S、Tendermint等项目中被广泛使用。相较于Go的Flag标准库,Cobra更加强大。

1 安装Cobra

go get github.com/spf13/cobra

2 直接举例

package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
)

var num0, num1 float64
var operation string

func main() {

	// 根命令
	rootCmd := cobra.Command{

		// 命令的名称
		Use: "compute",

		// 简短描述
		Short: "Arithmetic operation of two numbers",

		// 详细描述
		Long: "Computes the arithmetic result of two floating-point numbers, " +
			"including addition, subtraction, multiplication and division",
	}

	// 子命令
	operationCmd := &cobra.Command{
		Use:   "cal",
		Short: "Calculate two numbers",
		Long:  "Calculate the result of the addition operation of two numbers",

		// 钩子函数,命令执行时会调用
		RunE: func(cmd *cobra.Command, args []string) error {
			switch operation {
			case "add":
				fmt.Println(num0 + num1)
			case "sub":
				fmt.Println(num0 - num1)
			case "mul":
				fmt.Println(num0 * num1)
			case "div":
				if num1 == 0 {
					return fmt.Errorf("divisor is zero")
				}
				fmt.Println(num0 / num1)
			default:
				return fmt.Errorf("operation error")
			}
			return nil
		},
	}

	// 解析命令参数
	operationCmd.Flags().Float64Var(&num0, "num0", 0.0, "")
	operationCmd.Flags().Float64Var(&num1, "num1", 0.0, "")
	operationCmd.Flags().StringVar(&operation, "operation", "add", "")

	rootCmd.AddCommand(operationCmd) // 向根命令添加子命令

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

1.1 生成可执行文件

在这里插入图片描述

1.2 获取命令的帮助信息

在这里插入图片描述
在这里插入图片描述

1.3 命令测试

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值