Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a thread safe context that can be used downstream and mutated #4172

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

rubensayshi
Copy link

@rubensayshi rubensayshi commented Mar 3, 2025

It's currently unsafe to use c.Request.Context from the *gin.Context to pass to downstream functions AND do any mutations to the c.Request.Context.
Even when you do c.Request = c.Request.WithContext(...) you'll end up with the go race detector flagging the unsafe reading of the c.Request and writing to c.Request.

However it would be really nice to be able to put values into the *gin.Context with context.WithValue() in a thread-safe way that allows downstream usage of *gin.Context as context.Context to access those values.
For example, an auth middleware adding some debugging /loggin related values with context.WithValue() will not be lost along the way, or adding a otel.Tracer to the context with additional options etc.

Making all the places where gin touches c.Request thread-safe with a lock would be a significant undertaking and would have an impact on performance (probably talking about nano seconds, but still non zero impact).

With the MR we're adding a thread-safe way to carry around and mutate a context.Context inside *gin.Context without having to protect c.Request.

In practice the c.Request.Context isn't going to be very interesting to wrap anyway, so loosing that as the "root" context probably isn't a issue for anyone.
It's trivial to make the root InternalContext the c.Request.Context when we do .reset() (if ContextWithFallback is enabled), but I wanted to keep this MR as small as possible.
And it would have one quirky downside that if someone uses UseInternalContext and does something like c.Request = c.Request.WithContext(...) then it wouldn't have any effect.

There's a couple of mentions of issues around this before:

@rubensayshi rubensayshi changed the title add a thread safe context that can be used add a thread safe context that can be used downstream and mutated Mar 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant