更新到 Go 1.15 或更高版本后出现错误"panic: cannot create context from nil parent"



更新到Go 1.15后,当运行我的代码(单元测试)时,我得到这个错误:

panic: cannot create context from nil parent

gooutine 14 [running]:test . run .func1.2(0x1211480, 0x12a3dc8)/usr/local/opt/go/libexec/src/testing/testing.go:1143+0x332 testing.tRunner.func1(0xc000178900)/usr/local/opt/go/libexec/src/testing/testing.: 1146 + 0 x4b6恐慌(0 x1211480 0 x12a3dc8)/usr/local/opt/go/libexec/src/runtime/panic.: 965 + 0 x1b9上下文。WithValue(0x0, 0x0, 0x1210940, 0x12a3f58, 0x1241b80,0xc00007c910, 0x12a3f58, 0xc00004a770)/usr/local/opt/go/libexec/src/context/context.: 521 + 0 x187/usr/local/opt/go/libexec/src/context/context.: 521 + 0 x187github.com/myrepo/pkg/test.Test_failure (0 xc000765200)
/pkg/测试。: 43 + 0 x15f

这是我的代码:

ctx := context.WithValue(nil, "some string", nil)
req := http.Request{}
req = *req.WithContext(ctx)

如果您没有上游上下文,则使用context.Background()context.TODO()作为种子,如果您有,则传递该种子

你可以在这里看到文档说context.Background()应该被用作初始种子。https://pkg.go.dev/context背景

func后台¶function Background() ContextBackground返回一个非空的Context。它永远不会被取消,没有值,也没有截止日期。它通常由main函数、初始化和测试使用,并作为传入请求的顶级上下文。

一般情况下,你一开始就不应该把nil放在那里。

根据Go 1.15文档,不再允许传入nil父级:

现在显式地使用nil父对象创建派生上下文不允许。任何使用WithValue、WithDeadline或WithCancel函数会引起恐慌。

为了解决这个问题,我最终使用了context.TODO():
ctx := context.WithValue(context.TODO(), "some string", nil)

TODO返回一个非空的Context。代码应该使用上下文。待办事项当不清楚使用哪个上下文或还没有可用时(因为周围的功能还没有扩展到接受