首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-02-06 09:42:04
转载
826 人浏览过

从 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: %w\n", 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()

以上是从 cobra 子命令检索的上下文为空的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!