Update context to have a generic method for getting request data.#3329
Update context to have a generic method for getting request data.#3329cheikhshift wants to merge 2 commits intogin-gonic:masterfrom
Conversation
Add a generic method `GetAs` to get request data.
use method Get to get existing data.
|
|
||
| // GetAs returns the value for the given key, ie: (value, true). | ||
| // If the value does not exist it returns (nil, false) | ||
| func (c *Context) GetAs[T any](key string) (result T, exists bool) { |
There was a problem hiding this comment.
We also need support go1.16 up version.
There was a problem hiding this comment.
This will be problematic, as Generics were introduced in Go 1.19. Any suggestions?
There was a problem hiding this comment.
What's the benefit of this method over the non-generic version? The biggest issue with Get is that a failed type assertion causes a run-time panic, which seems to be the same here?
There was a problem hiding this comment.
No need to assert the variable to a certain type. The assertion is also checked and returns true/false depending on the case.
There was a problem hiding this comment.
@appleboy gin requires go 1.21 or above now. Would you consider this feature again??
There was a problem hiding this comment.
The changing is not with exported generic function which is not for general use
Why not you choosing this pr??
Exported generic function is much useful for develoepr who use gin
|
I would find adding this method to be very useful, if support for an older Go version (perhaps in a new Gin release) would no longer be required. If passing custom types in the request context, it helps avoiding some of the code duplication incurred by using the To give a concrete example, in this project I am working on it would've helped to avoid having to define a custom function when retrieving context parameters that are of custom type. I could've used this id := ctx.GetInt("id")
req, ok := common.CtxGetTyped[casheerapi.UpdateEntryRequest](ctx, "req")
if !ok {
return
}With that method, I wouldn't have had to define my custom method
Avoiding the code duplication by doing the type assertions yourself is a good enough benefit IMO. Functions like |
|
I think we don't need the changes from #3633 anymore. |
Add a generic method
GetAsto get request data.master