Skip to content

Router in runtime breaks Context for any following middlewaresΒ #375

@mjuraga

Description

@mjuraga

Describe the bug

I have some logic where I need to log the request after the authentication and authorization, and in my auth functions I set something like:

ctx := context.WithValue(r.Context(), types.AuthErrCtxKey, retErr)
*r = *r.WithContext(ctx)

And after the request is executed, my context is gone due to the following line:

next.ServeHTTP(rw, rCtx)

		if _, rCtx, ok := ctx.RouteInfo(r); ok {
			next.ServeHTTP(rw, rCtx)
			return
		}

This creates a new rCtx and passes it up to the downstream handlers, but never sets it to the r variable, which means everything done to this request object, most importantly Context, never gets to the upstream handlers after this return.

Steps to Reproduce

If you add a middleware before your router, and one after. Add some Context value in the one after, and try to read it in the one before, it will be gone.

Expected behavior

I would expect anything done with request.Context survives for the lifetime of the request.

Actual behavior

From this point in the request lifetime anything added or changed will not be reflected in the chain before.

Environment
Not-applicable

Additional context

I would be happy to provide an upstream fix for this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions