【发布时间】:2021-10-20 17:27:31
【问题描述】:
更新到 Go 1.15 后,运行代码(单元测试)时出现此错误:
恐慌:无法从 nil 父级创建上下文
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 context.WithValue(0x0, 0x0, 0x1210940, 0x12a3f58, 0x1241b80, 0xc00007c910, 0x12a3f58, 0xc00004a770) /usr/local/opt/go/libexec/src/context/context.go:521 +0x187 /usr/local/opt/go/libexec/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)
【问题讨论】:
-
文档总是说“不要传递 nil 上下文,即使函数允许它”
-
是的,这从来都不是一个好主意。然而,这是可能的,也是允许的。 :)
-
这真的不仅仅是“不是一个好主意”——它直接违背了文档告诉你的做法。
-
不幸的是,有无数不正确但可能发生的事情。文档始终是最好的起点。
标签: go