如何在GO中使用继承的上下文

发布于 2025-01-17 22:23:29 字数 1167 浏览 0 评论 0原文

我正在Go中写一个Kubernetes操作员。我正在为给定上下文对象的清洁处理而苦苦挣扎。将继承上下文作为参数以进一步的方法是一种好习惯。当不这样做时,Linter会显示以下消息:

instance, err := k8sConnector.getInstance(r.ctx, req.NamespacedName)
root@8794fe3af767:/go/xpro-update-manager# golangci-lint run --timeout=15m  ./...
controllers/release_controller.go:79:43: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
        instance, err := k8sConnector.getInstance(r.ctx, req.NamespacedName)
                                                 ^

但是(如

    k8sContext, cancel := context.WithCancel(r.ctx)
    defer cancel()

    instance, err := k8sConnector.getInstance(k8sContext, req.NamespacedName)
root@8794fe3af767:/go/xpro-update-manager# golangci-lint run --timeout=15m  ./...
controllers/xprorelease_controller.go:79:43: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
        instance, err := k8sConnector.getInstance(k8sContext, req.NamespacedName)
                                                 ^

​在我看来,衬里有一个假阳性,因为在我看来,这确实是一个继承的上下文,与Linter所说的相反。

I am writing an Kubernetes Operator in Go. I am struggling with the clean handling of the given context object. It is a good practice to to pass an inherited context as a parameter to further methods. When doing not so the linter shows the following messages:

instance, err := k8sConnector.getInstance(r.ctx, req.NamespacedName)
root@8794fe3af767:/go/xpro-update-manager# golangci-lint run --timeout=15m  ./...
controllers/release_controller.go:79:43: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
        instance, err := k8sConnector.getInstance(r.ctx, req.NamespacedName)
                                                 ^

But when doing so (as documented in https://pkg.go.dev/context#WithCancel) the linter shows the same message:

    k8sContext, cancel := context.WithCancel(r.ctx)
    defer cancel()

    instance, err := k8sConnector.getInstance(k8sContext, req.NamespacedName)
root@8794fe3af767:/go/xpro-update-manager# golangci-lint run --timeout=15m  ./...
controllers/xprorelease_controller.go:79:43: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
        instance, err := k8sConnector.getInstance(k8sContext, req.NamespacedName)
                                                 ^

What is the correct handling of the context object? It seems to me that the linter has a false positive because in my opinion it is indeed a inherited context which I am passing in contrast to what the linter says.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文