Nil pointer dereference in context

Is the line https://github.com/golang/go/blob/138d2c9b88d9e3d5adcebf9cb7c356b43d6a9782/src/context/context.go#L566

return c.Context.Value(key)

Concurrent Safe?

The stack trace of error I am receiving is attached

This panic is arising when a lot of read is happening to context value.

Yes, Context.Value is thread/goroutine-safe. I can’t tell from this snippet of code what the issue is. Why are you redacting out one of the lines of the stack trace?

The stack contains the repo information for which our organization has asked us not to expose it anywhere. That’s why i had to redact it.

I can provide some information though.
For every request, we put this in request context.

*r = *r.WithContext(ctx.WithValue(r.Context(), appData, &sync.Map{}))

And fetch it

if data, ok := ctx.Value(appData).(*sync.Map); ok {        //here is the panic happening
		data.Range(func(key, value interface{}) bool {
			if k, ok := key.(string); ok {
				appData[k] = value
			}

			return true
		})
	}

All this happens through middleware.

This is not threadsafe/goroutine-safe on all machine architectures.

EDIT: This is wrong; I was thinking this was storing to a pointer, but I suspect it’s actually storing to the Request struct which is definitely not threadsafe.

Ranging over the data *sync.Map won’t access invalid memory, but it is non-deterministic, so if other goroutines are adding/removing elements, you don’t know what you’ll get.

It looks like appData is a (potentially global?) map and you’re writing into it. This is not threadsafe/goroutine-safe.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.