-
Notifications
You must be signed in to change notification settings - Fork 32
/
ctx.go
60 lines (50 loc) · 993 Bytes
/
ctx.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package utils
import (
"context"
"reflect"
"strconv"
)
func GetValue[T any](c context.Context, key string) (T, bool) {
val, ok := getValue[T](c, key)
if !ok {
return *new(T), false
}
v, ok := val.(T)
if !ok {
return *new(T), false
}
return v, true
}
func getValue[T any](c context.Context, key string) (interface{}, bool) {
val := c.Value(key)
if val == nil {
return *new(T), false
}
if reflect.TypeOf(*new(T)).Kind() == reflect.Int && reflect.TypeOf(val).Kind() == reflect.String {
strconvInt, err := strconv.Atoi(val.(string))
if err != nil {
return *new(T), false
}
return strconvInt, true
}
v, ok := val.(T)
if !ok {
return *new(T), false
}
return v, true
}
func GetIntValueFromStr(c context.Context, key string) (int, bool) {
val := c.Value(key)
if val == nil {
return 0, false
}
v, ok := val.(string)
if !ok {
return 0, false
}
strconvInt, err := strconv.Atoi(v)
if err != nil {
return 0, false
}
return strconvInt, true
}