-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
105 lines (80 loc) · 1.75 KB
/
utils.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package service
import (
// "errors"
"reflect"
"strconv"
)
type ParamItem struct {
Key string
Value string
Values []string
}
func (p ParamItem) AsInt() int {
intVar, _ := strconv.Atoi(p.Value)
return intVar
}
func (p ParamItem) SetValue(value string) {
p.Value = value
p.Values = []string{value}
}
func (p *ParamItem) SetValues(values []string) {
if len(values) > 0 {
p.Value = values[0]
}
p.Values = values
}
type ParamHolder interface {
Get(string) (ParamItem, bool)
}
// i would like to make pagination params optional, maybe adding a fallback
// value to the param tag
// `param:"page,1"`
func parseParam(tagName string, v interface{}, params ParamHolder) error {
t := reflect.TypeOf(v).Elem()
rv := reflect.ValueOf(v).Elem()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
tag, ok := field.Tag.Lookup(tagName)
if !ok {
continue
}
val, ok := params.Get(tag)
if !ok {
continue
}
fv := rv.FieldByName(field.Name)
if ok := fv.CanSet(); !ok {
continue
}
setVal(fv, val.Value)
}
return nil
}
func setVal(fv reflect.Value, val interface{}) {
switch fv.Kind() {
case reflect.Ptr:
handlePtr(fv, val)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if value, err := strconv.ParseInt(val.(string), 10, 64); err == nil {
fv.SetInt(value)
}
case reflect.String:
fv.SetString(val.(string))
case reflect.Bool:
fv.SetBool(val == "true")
case reflect.Float64:
if value, err := strconv.ParseFloat(val.(string), 64); err == nil {
fv.SetFloat(value)
}
}
}
func handlePtr(fv reflect.Value, val interface{}) {
if val == nil {
src := reflect.Zero(fv.Type())
fv.Set(src)
return
}
fv.Set(reflect.New(fv.Type().Elem()))
deref := fv.Elem()
setVal(deref, val)
}