Update context to have a generic method.

Add a generic method `GetAs` to get request data.
This commit is contained in:
Cheikh Seck 2022-09-19 12:00:08 +00:00 committed by GitHub
parent 814cd188eb
commit 84bae816a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 0 deletions

View File

@ -265,6 +265,20 @@ func (c *Context) Get(key string) (value any, exists bool) {
return
}
// 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) {
c.mu.RLock()
value, exists := c.Keys[key]
c.mu.RUnlock()
if !exists {
return
}
result, exists = value.(T)
return
}
// MustGet returns the value for the given key if it exists, otherwise it panics.
func (c *Context) MustGet(key string) any {
if value, exists := c.Get(key); exists {