1
votes

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)
2
The docs have always said “Do not pass a nil Context, even if a function permits it”JimB
Yes, it was never a good idea. It was, however, possible and allowed. :)Nic
It's really more than just "not a good idea" — it was directly against what the docs were telling you to do.Bruno Reis
Unfortunately there are an uncountable number of things that are incorrect but possible. The documentation is always the best place to start.JimB

2 Answers

2
votes

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.

0
votes

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).