首页 > 解决方案 > 通用函数中的 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是我想在其他命令中使用它的东西,我不想重复相同的标志。

标签: gocommand-line-interfacego-cobracobra

解决方案


您按价值传递optsGetCommandFlags。您应该传递一个指向它的指针,因此为标志注册的地址使用opts调用函数中声明的地址。

func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
  ...
}

推荐阅读