gin icon indicating copy to clipboard operation
gin copied to clipboard

Update context to have a generic method for getting request data.

Open cheikhshift opened this issue 3 years ago • 2 comments

Add a generic method GetAs to get request data.

  • With pull requests:
    • Open your pull request against master
    • Your pull request should have no more than two commits, if not you should squash them.
    • It should pass all tests in the available continuous integration systems such as GitHub Actions.
    • You should add/modify tests to cover your proposed code changes.
    • If your pull request contains a new feature, please document it on the README.

cheikhshift avatar Sep 19 '22 12:09 cheikhshift

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 ctx.Get() method followed by a type assertion.

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 GetAs in the same way I used GetInt. (code for reference)

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 CtxGetType which does the same as the new GetAs (actually it does more things for the sake of safety, but I could've omitted them because a middleware is validating the type beforehand).

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?

Avoiding the code duplication by doing the type assertions yourself is a good enough benefit IMO. Functions like GetInt, GetBool, GetTime etc. that are already defined for the library do pretty much the same, except they convert the value to an existing type. If we have those, I would argue that this new function would be just as useful.

Ozoniuss avatar Jun 20 '23 14:06 Ozoniuss

I think we don't need the changes from https://github.com/gin-gonic/gin/pull/3633 anymore.

appleboy avatar Sep 15 '24 01:09 appleboy