Reputation: 12846
After updating to Go 1.15 I'm getting this error when running my code (a unit test):
panic: cannot create context from nil parent
goroutine 14 [running]: 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 panic(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
This is my code:
ctx := context.WithValue(nil, "some string", nil)
req := http.Request{}
req = *req.WithContext(ctx)
Upvotes: 1
Views: 3313
Reputation: 100
Either use context.Background()
or context.TODO()
as seed if you do not have an upstream context, if you have then pass that one.
You can see here that the docs say context.Background() should be used as initial seed. https://pkg.go.dev/context#Background
func Background ¶ func Background() Context Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.
Generally you shouldn't have put nil there in the first place.
Upvotes: 2
Reputation: 12846
According to the Go 1.15 documentation passing in a nil parent is not allowed anymore:
Creating a derived Context using a nil parent is now explicitly disallowed. Any attempt to do so with the WithValue, WithDeadline, or WithCancel functions will cause a panic.
To fix the issue I ended up using context.TODO():
ctx := context.WithValue(context.TODO(), "some string", nil)
TODO returns a non-nil, empty Context. Code should use context.TODO when it's unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).
Upvotes: 1