go - 通用函数中的 Golang Cobra 命令标志未从 cli 获取值
问题描述
我正在将我的 cobra 命令移动flags
到一个函数中,以便可以在其他命令中使用它。我可以看到命令,但是当我输入标志时它总是返回false
。
以下是我的代码:
func NewCommand(ctx context.Context) *cobra.Command {
var opts ListOptions
cmd := &cobra.Command{
Use: "list",
Short: "List",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println(args) // []
opts.refs = args
return List(ctx, gh, opts, os.Stdout)
},
}
cmd = GetCommandFlags(cmd, opts)
return cmd
}
// GetListCommandFlags for list
func GetCommandFlags(cmd *cobra.Command, opts ListOptions) *cobra.Command {
flags := cmd.Flags()
flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")
flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")
return cmd
}
所以当我输入以下命令时
data-check list --ignore-latest
的标志值--ignore-latest
应该是true
,但我在args中得到false
一个值。RunE
我在这里错过了什么吗?
GetCommandFlags
是我想在其他命令中使用它的东西,我不想重复相同的标志。
解决方案
您按价值传递opts
给GetCommandFlags
。您应该传递一个指向它的指针,因此为标志注册的地址使用opts
调用函数中声明的地址。
func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
...
}
推荐阅读
- python - 为什么 Python 在列表理解中不排除错误
- php - 尝试在 null 上读取属性“total_product_quantity”
- mongodb - Mongo DB 存档无法从 ec2 与 vpc 对等互连
- django - 无法解析相关模型。姜戈,左塞尔
- .net - 使用 Directory.Build.Prop 为 .NET Framework 添加包
- python - 为电报机器人设置速率限制逻辑?
- c - 定义一个使用数组作为输入的函数
- actions-on-google - Google 上的操作 + 交互式画布游戏 + 设备定位
- spring-boot - 将spring-data-jpa与hibernate用作jpa提供程序时的对象/实体生命周期?
- java - 尝试通过 putty 编译 java 程序时出现以下错误:预期的类、接口或枚举