You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Go到1.15及以上运行单元测试报panic: cannot create context from nil parent错误

错误触发原因

Go 1.15 针对 context 标准库新增了父上下文非空校验逻辑:在低于 1.15 的 Go 版本中,给 context.WithValue、context.WithCancel 这类派生上下文的方法传入 nil 作为父参数是被允许的,底层会默认返回一个空的上下文实现,不会抛出异常。但从 1.15 版本开始,官方在上下文派生方法的入口处新增了非空校验,只要父上下文为 nil 就会直接触发 cannot create context from nil parent panic。

你代码中的 ctx := context.WithValue(nil, "some string", nil) 一行直接传入了 nil 作为父上下文,刚好触发了该校验规则。

解决方法

按照你的使用场景,从以下方案中选择即可:

  • 如果你需要一个无业务语义的根上下文作为父节点,将 nil 替换为 context.Background() 即可,修改后代码如下:
ctx := context.WithValue(context.Background(), "some string", nil)
req := http.Request{}
req = *req.WithContext(ctx)
  • 如果你是在测试场景下使用、后续可能会调整上下文的传入逻辑,也可以使用语义更贴合的 context.TODO() 作为根上下文:
ctx := context.WithValue(context.TODO(), "some string", nil)
req := http.Request{}
req = *req.WithContext(ctx)
  • 如果你不需要在上下文中存自定义值,也可以直接把根上下文传入 WithContext 方法,不需要额外调用 WithValue 派生。

内容的提问来源于stack exchange,提问作者Nic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:27:03