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 获取命令的帮助信息