-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathcontext_generic.go
More file actions
43 lines (34 loc) · 1.23 KB
/
context_generic.go
File metadata and controls
43 lines (34 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package echo
import "errors"
// ErrNonExistentKey is error that is returned when key does not exist
var ErrNonExistentKey = errors.New("non existent key")
// ErrInvalidKeyType is error that is returned when the value is not castable to expected type.
var ErrInvalidKeyType = errors.New("invalid key type")
// ContextGet retrieves a value from the context store or ErrNonExistentKey error the key is missing.
// Returns ErrInvalidKeyType error if the value is not castable to type T.
func ContextGet[T any](c *Context, key string) (T, error) {
c.lock.RLock()
defer c.lock.RUnlock()
val, ok := c.store[key]
if !ok {
var zero T
return zero, ErrNonExistentKey
}
typed, ok := val.(T)
if !ok {
var zero T
return zero, ErrInvalidKeyType
}
return typed, nil
}
// ContextGetOr retrieves a value from the context store or returns a default value when the key
// is missing. Returns ErrInvalidKeyType error if the value is not castable to type T.
func ContextGetOr[T any](c *Context, key string, defaultValue T) (T, error) {
typed, err := ContextGet[T](c, key)
if err == ErrNonExistentKey {
return defaultValue, nil
}
return typed, err
}