Custom values in the request context #2
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Sometimes we have the neccesity to set a session object, mark a request as white list, set some var/object in the request context, thinks like that into the middlewares, and this neccesity depents on many situations and the kind of our web api.
The proposal is to have a customValues object in context struct, but defined only when is going to be used, like follow:
With two methods to interact with it:
And the way that we can use it, is somethig like this:
So, that is my initial approximation, but let me know what do you think about that and if you are agree about the feature, or what is the best way to implement it?
Maybe is a better option to have this feature into the request and no in context?
Let me know!!
Since
Context
is an interface, you can just provide your own context:However, this doesn't work right now because
ctx.Next
doesn't accept an additional parameter.This could be added with a trivial 1-2 line change in
ctx.Next
.Then it can be consumed with type safety:
I've added this in
c5cf8488b3
let me know if this works for you![PROPOSAL]: Feature to support custom values into the request contextto Custom values in the request context@ed wrote in #2 (comment):
Hey @ed I like it, I believe your approach is simple because it remove the overhead about Reflection, but there are two things that maybe can carry with unexpected situations, one more or less complicated and the other one is manegeable:
Situations:
Line
custom := ctx.(*Custom)
orreturn ctx.Next(ctx.(*Custom))
Observation:
The other way to avoid the problems with cast Panic without add the safeCast function, is take care in the first middleware chain to create in a safe way the Custom object to avoid problems, somethink like this:
So in that way, the rest of the middleware chain, the cast for Custom is naturally safe.
Let me know your point of view, but I think your approach is a good and performanced solution.
Hi,
both of these points are based on the assumption that you have to cast to
*Custom
on everyctx.Next
call.However, that is not the case:
An interface is a 16-byte structure containing the type and the pointer. As long as interfaces are passed to interface parameters by value, all of that type and pointer information gets passed along.
You don't need to cast to
*Custom
everywhere down the chain and you don't need asafeCast
function because it's guaranteed to be your custom context type.Hi man, you're right, so your implemention works. TK!!