-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.go
84 lines (75 loc) · 1.75 KB
/
form.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
package helpers
import (
"net/http"
"net/url"
"reflect"
"strconv"
"github.com/stellar/go/support/errors"
)
// FromRequest will populate destination fields using http.Request post values.
func FromRequest(r *http.Request, destination interface{}) error {
rvalue := reflect.ValueOf(destination).Elem()
typ := rvalue.Type()
for i := 0; i < rvalue.NumField(); i++ {
tag := typ.Field(i).Tag.Get("form")
switch tag {
case "":
case "-":
continue
default:
value := r.PostFormValue(tag)
if value == "" {
continue
}
switch rvalue.Field(i).Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(value)
if err != nil {
return err
}
rvalue.Field(i).SetBool(b)
case reflect.String:
rvalue.Field(i).SetString(value)
default:
return errors.New("Invalid value: " + value + " type for type: " + tag)
}
}
}
s, special := destination.(SpecialValuesConvertable)
if special {
err := s.FromRequestSpecial(r, destination)
if err != nil {
return errors.Wrap(err, "Error from FromRequestSpecial")
}
}
return nil
}
// ToValues will create url.Values from source.
func ToValues(source interface{}) url.Values {
values := make(url.Values)
rvalue := reflect.ValueOf(source).Elem()
typ := rvalue.Type()
for i := 0; i < rvalue.NumField(); i++ {
field := rvalue.Field(i)
tag := typ.Field(i).Tag.Get("form")
if tag == "" || tag == "-" {
continue
}
switch field.Interface().(type) {
case bool:
value := rvalue.Field(i).Bool()
values.Set(tag, strconv.FormatBool(value))
case string:
value := rvalue.Field(i).String()
if value == "" {
continue
}
values.Set(tag, value)
}
}
s, special := source.(SpecialValuesConvertable)
if special {
s.ToValuesSpecial(values)
}
return values
}