如何提取注册信息?

How to extract registered information?

我在我的 Golang 应用程序中使用 cobra。如何获取我在 Cobra 注册的命令和值的列表。

如果我添加一个 root 命令,然后添加一个 DisplayName 命令。

var Name = "sample_"
var rootCmd = &cobra.Command{Use: "Use help to find out more options"}
rootCmd.AddCommand(cmd.DisplayNameCommand(Name))

我能否通过使用某些 Cobra 函数从我的程序中知道 Name 的值是什么?理想情况下,我想访问 Name 中的这个值并用它来检查一些逻辑。

您可以使用存储在 Name 变量中的值在您的程序中执行操作。 cobra 的用法示例是:

var Name = "sample_"

var rootCmd = &cobra.Command{
    Use:   "hello",
    Short: "Example short description",
    Run:   func(cmd *cobra.Command, args []string) {
        // Do Stuff Here
    },
}

var echoCmd = &cobra.Command{
    Use:   "echo",
    Short: "Echo description",
    Run:   func(cmd *cobra.Command, args []string) {
        fmt.Printf("hello %s", Name)
    },
}

func init() {
    rootCmd.AddCommand(echoCmd)
}

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

`

在上面的代码中,可以看到hello是根命令,echo是子命令。如果您执行 hello echo,它将回显存储在 Name 变量中的值 sample_

您也可以这样做:

var echoCmd = &cobra.Command{
    Use:   "echo",
    Short: "Echo description",
    Run:   func(cmd *cobra.Command, args []string) {
        // Perform some logical operations
        if Name == "sample_" {
            fmt.Printf("hello %s", Name)
        } else {
            fmt.Println("Name did not match")
        }
    },
}

想了解更多cobra的使用方法,你也可以从下面link.

查看我的项目

https://github.com/bharath-srinivas/nephele

希望对您有所帮助。