卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34183本站已运行391

从 cobra 子命令检索的上下文为空

从 cobra 子命令检索的上下文为空

问题内容

我想要一个全局超时(在 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()

卓越飞翔博客
上一篇: 在排列上应用处理程序,而不需要级别缓存?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏