/
bind.go
115 lines (98 loc) · 2.69 KB
/
bind.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
106
107
108
109
110
111
112
113
114
115
package bind
import (
"encoding/json"
"errors"
"net/http"
"reflect"
"strings"
validator "gopkg.in/go-playground/validator.v9"
)
// IRouter extracts a URL parameter value.
type IRouter interface {
Param(r *http.Request, param string) string
}
// Binder contains the request bind an validator objects.
type Binder struct {
validator *validator.Validate
router IRouter
}
// New returns a new binder for request bind and validation.
func New(r IRouter) *Binder {
return &Binder{
validator: validator.New(),
router: r,
}
}
// UnmarshalAndValidate will unmarshal and validate a struct using the validator.
func (b *Binder) UnmarshalAndValidate(s interface{}, r *http.Request) (err error) {
if err = b.Unmarshal(s, r); err != nil {
return
} else if err = b.Validate(s); err != nil {
return
}
return
}
// Validate will validate a struct using the validator.
func (b *Binder) Validate(s interface{}) error {
return b.validator.Struct(s)
}
// Unmarshal will perform an unmarshal on an interface using: form or JSON.
func (b *Binder) Unmarshal(iface interface{}, r *http.Request) (err error) {
// Check for errors.
v := reflect.ValueOf(iface)
if v.Kind() != reflect.Ptr {
return errors.New("must pass a pointer, not a value")
}
// Load the map.
m := make(map[string]interface{})
// Try to auto detect data type based on on the header.
// Header can having multiple values separated by a semicolon.
ct := r.Header.Get("Content-Type")
switch true {
case ct == "", strings.Contains(ct, "application/x-www-form-urlencoded"):
// Parse the form.
err = r.ParseForm()
if err != nil {
return err
}
for k, vv := range r.Form {
m[k] = vv[0]
}
case strings.Contains(ct, "application/json"):
// Decode to the interface.
err = json.NewDecoder(r.Body).Decode(&m)
r.Body.Close()
if err != nil {
// No longer fail on an unmarshal error. This is so users can submit
// empty data for GET requests, yet we can still map the URL
// parameter by using the same logic.
}
// Copy the map items to a new map.
mt := make(map[string]interface{})
for key, value := range m {
mt[key] = value
}
// Save the map to the body to handle cases where there is a body
// defined.
m["body"] = mt
}
// Loop through each field to extract the URL parameter.
elem := reflect.Indirect(v.Elem())
keys := elem.Type()
for j := 0; j < elem.NumField(); j++ {
tag := keys.Field(j).Tag
tagvalue := tag.Get("json")
pathParam := b.router.Param(r, tagvalue)
if len(pathParam) > 0 {
m[tagvalue] = pathParam
}
}
// Convert to JSON.
var data []byte
data, err = json.Marshal(m)
if err != nil {
return
}
// Unmarshal to the interface from JSON.
return json.Unmarshal(data, &iface)
}