首頁  >  文章  >  後端開發  >  從 cobra 子指令檢索的上下文為空

從 cobra 子指令檢索的上下文為空

WBOY
WBOY轉載
2024-02-06 09:42:04828瀏覽

从 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刪除