atreugo icon indicating copy to clipboard operation
atreugo copied to clipboard

AttachContext overrides previous AttachContext

Open ayeletdeRoos opened this issue 2 years ago • 2 comments

Hi,

I have a scenario where my REST api service calls 2 middlewares. both of them use the AttachContext before calling ctx.Next().

After a long debug I realized that the second AttachContext is overriding the first one since the AttachContext key is the same one generated here .

Is this intentional?

Thanks in advance

ayeletdeRoos avatar Sep 19 '23 12:09 ayeletdeRoos

Hi @ayeletdeRoos,

Yes, it is. The point of AttachContext is to save a second context in the RequestCtx, but only one! If you need to save more than one, you can create a new one from the first context, and reattach it to the request!

Something like this:

// NOTE: ctx => atreugo.RequestCtx

myCtx := ctx.AttachedContext()
myBothCtx := context.WithValue(myCtx, <key>, mySecondCtx)

ctx.AttachContext(myBothCtx)

When you attach the last context, all values are accesible via ctx.Value(...)

savsgio avatar Sep 20 '23 08:09 savsgio

Hi @savsgio ,

Right, I did a similar workaround - thanks!

I do think a check for this "edge" case can be helpful (if a key is overridden in the ctx)

Thanks again for your reply :)

ayeletdeRoos avatar Sep 20 '23 15:09 ayeletdeRoos