From 84bae816a02a20fca8acc72c1fcb70bbf6c9c86b Mon Sep 17 00:00:00 2001 From: Cheikh Seck Date: Mon, 19 Sep 2022 12:00:08 +0000 Subject: [PATCH 1/2] Update context to have a generic method. Add a generic method `GetAs` to get request data. --- context.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/context.go b/context.go index f9489a77..3dc89a4c 100644 --- a/context.go +++ b/context.go @@ -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 { From 0d9e3d19aff81c1fc40fbaea901c99b08ff48ad7 Mon Sep 17 00:00:00 2001 From: Cheikh Seck Date: Mon, 19 Sep 2022 12:06:54 +0000 Subject: [PATCH 2/2] Update context.go use method Get to get existing data. --- context.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/context.go b/context.go index 3dc89a4c..3d3cc33b 100644 --- a/context.go +++ b/context.go @@ -268,13 +268,11 @@ func (c *Context) Get(key string) (value any, exists bool) { // 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() - + value, exists := c.Get(key) if !exists { return } + result, exists = value.(T) return }