Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Context的错误使用引发Panic的问题复盘 | 编程沉思录 #68

Open
chenyahui opened this issue May 6, 2024 · 1 comment
Open

Comments

@chenyahui
Copy link
Owner

https://www.cyhone.com/articles/context-to-panic/

我们有这么一段业务代码,在 Gin 的 API Handler 中,开了一个子 goroutine 写 DB,代码大概是这样: package main import ( "github.com/gin-gonic/gin" "gorm.io/gorm" ) var db *gorm.DB func Ech

@jiekun
Copy link

jiekun commented Jun 11, 2024

很有趣的文章,感谢分享。

关注到一些小的细节:

  1. 子 goroutine 中可以用context.Background()创建一个新的 context 对象 ,和外部接口主逻辑的 context 分离开

    • 通过上下文猜测,看起来是希望父子 goroutine 的生命周期不用保持一致,context 里面的其他信息其实还是有可能使用上的,例如用于生成 Trace Span,所以用空白 context 不够好,不过在具体的业务场景里是最高效、不引入额外复杂度解决问题的👍🏻。
  2. 我们之后应该如何避免: 方法三

    • 几个方法看起来都很棒!不过 ContextWithFallback 本质上是个 Feature,感觉核心矛盾还是它的实际使用不符合预期。会不会在放回 sync.Pool 之前做检查会更好呢,或者任何用户不感知的方案?因为这个 Feature 最初在 v1.8.0 是没有提供 Flag 的,然后用户报障之后新增了 ContextWithFallback。所以是还存在类似的问题,未来用户再提起可能还是要修复 :)
    • gin.Context.Copy 这个方案细想不知道会不会不容易推行,gin.Context 实现 context.Context 接口,所以它在很多方法里会被用作 context.Context 传递,因此在深层的方法中也会被直接 go myFunc(ctx, a, b, c) 执行。而这类方法在设计上通常是不要求检查 ctx 是 context.Context 还是 gin.Context 的,所以感觉解决 sync.Pool 的使用姿势会更可靠一些

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants