首页 > 解决方案 > 更新到 Go 1.15 或更高版本后出现错误“panic: cannot create context from nil parent”

问题描述

更新到 Go 1.15 后,运行代码(单元测试)时出现此错误:

恐慌:无法从零父级创建上下文

goroutine 14 [运行]: testing.tRunner.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.go:1146 +0x4b6 恐慌(0x1211480,0x12a3dc8)/usr/local/opt/go/libexec/src/runtime/panic.go:965 +0x1b9 上下文。 WithValue(0x0, 0x0, 0x1210940, 0x12a3f58, 0x1241b80, 0xc00007c910, 0x12a3f58, 0xc00004a770) /usr/local/opt/go/libexec/src/context/context.go:521 +0x187 /usr/local/opt/go/lib /src/context/context.go:521 +0x187 github.com/myrepo/pkg/test.Test_failure(0xc000765200)
/pkg/test.go:43 +0x15f

这是我的代码:

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

标签: go

解决方案


如果您没有上游上下文,则使用context.Background()或作为种子,如果您有然后通过该上下文。context.TODO()

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

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

一般来说,你一开始就不应该把 nil 放在那里。


推荐阅读