mirror of https://github.com/gin-gonic/gin.git
Update context to have a generic method.
Add a generic method `GetAs` to get request data.
This commit is contained in:
parent
814cd188eb
commit
84bae816a0
14
context.go
14
context.go
|
@ -265,6 +265,20 @@ func (c *Context) Get(key string) (value any, exists bool) {
|
||||||
return
|
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.
|
// MustGet returns the value for the given key if it exists, otherwise it panics.
|
||||||
func (c *Context) MustGet(key string) any {
|
func (c *Context) MustGet(key string) any {
|
||||||
if value, exists := c.Get(key); exists {
|
if value, exists := c.Get(key); exists {
|
||||||
|
|
Loading…
Reference in New Issue