升级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
相关产品推荐
相关产品推荐

