-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconvect.go
More file actions
79 lines (69 loc) · 1.64 KB
/
convect.go
File metadata and controls
79 lines (69 loc) · 1.64 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
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
package params
import (
"reflect"
"strconv"
"strings"
)
// Convert converts the values in the http.Request's query string to the fields of the provided struct.
func Convert(values map[string][]string, v interface{}) error {
rv := reflect.ValueOf(v).Elem()
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
fv := rv.Field(i)
ft := rt.Field(i)
// Skip unexported fields.
if ft.PkgPath != "" {
continue
}
tag := ft.Tag.Get("param")
if tag == "" {
continue
}
name, defaultValue := parseTag(tag)
if values[name] == nil {
if defaultValue != "" {
values[name] = []string{defaultValue}
} else {
continue
}
}
// Set the field's value.
switch fv.Kind() {
case reflect.String:
fv.SetString(values[name][0])
case reflect.Bool:
b, err := strconv.ParseBool(values[name][0])
if err != nil {
return err
}
fv.SetBool(b)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(values[name][0], 10, 64)
if err != nil {
return err
}
fv.SetInt(n)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
n, err := strconv.ParseUint(values[name][0], 10, 64)
if err != nil {
return err
}
fv.SetUint(n)
case reflect.Float32, reflect.Float64:
n, err := strconv.ParseFloat(values[name][0], fv.Type().Bits())
if err != nil {
return err
}
fv.SetFloat(n)
}
}
return nil
}
func parseTag(tag string) (name string, defaultValue string) {
parts := strings.Split(tag, ",")
name = parts[0]
if len(parts) > 1 {
defaultValue = parts[1]
}
return name, defaultValue
}