首页 > 文章列表 > 没有在 cobra 子命令中找到相关上下文

没有在 cobra 子命令中找到相关上下文

498 2024-02-15
问题内容

我想要一个全局超时(在 rootCmd 中设置),因此我在 rootCmd 中设置如下

ctxInit := context.Background()
timeout := viper.GetInt("timeout")
ctx, cancel := context.WithTimeout(ctxInit, time.Duration(timeout)*time.Second)
defer cancel()
cmd.SetContext(ctx)

然后在子命令中

ctx := rootCmd.Context()

但是 ctxcontext.emptyCtx {}

我在设置/检索上下文方面做错了什么吗?

编辑

我的 rootCmd 声明

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
    Use:              "my-cli",
    TraverseChildren: true,
    Short:            "cli",
    PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
        var err error
        logger, err = logging.InitialiseLogger(*logLevel, *logFormat)
        if err != nil {
            return err
        }
        if err := viper.BindPFlags(cmd.Flags()); err != nil {
            return fmt.Errorf("error binding flags to %s command: %wn", cmd.Name(), err)
        }
        if err := cloneMethodValidator(cmd); err != nil {
            return err
        }
        if err := InitConfig(false); err != nil {
            logger.Fatal("ERROR initiating configuration:n", err)
        }
        ctxInit := context.Background()
        timeout := viper.GetInt("timeout")
        ctx, cancel := context.WithTimeout(ctxInit, time.Duration(timeout)*time.Second)
        defer cancel()
        cmd.SetContext(ctx)
        return nil
    },
}


正确答案


正如@Peter提到的,cmd和rootCmd不一样。 Cobra文档描述了PersistentPreRun(E)

所以 cmd.SetContext(ctx) 没有设置 rootCmd 的上下文,而是设置子命令的上下文。

然后在子命令中,您可以使用:

ctx := cmd.Context()

而不是 rootCmd.Context()