我在我的 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
,它将回显存储在 sample_
变量中的值 Name
。
你也可以这样做:
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的信息,您还可以从下面的链接查看我的项目。
https://github.com/bharath-srinivas/nephele
希望这有帮助。