-
Notifications
You must be signed in to change notification settings - Fork 1
/
injector.go
246 lines (224 loc) · 5.52 KB
/
injector.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package rubik
import (
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"github.com/rubikorg/rubik/internal/checker"
"github.com/rubikorg/rubik/pkg"
"github.com/pkg/errors"
"github.com/julienschmidt/httprouter"
)
// inject is the the entry point of request injection in rubik
// an injection is a process of reading the
func inject(req *http.Request,
pm httprouter.Params, en interface{}, v Validation) (interface{}, error) {
// lets check what type of request it is
ctype := req.Header.Get(Content.Header)
var body = make(map[string]interface{})
var params = make(map[string]string)
// check if any params in the route
if len(pm) > 0 {
for _, p := range pm {
exportedKey := capitalize(p.Key)
params[exportedKey] = p.Value
}
}
b, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
switch ctype {
case Content.JSON:
err = json.Unmarshal(b, &body)
if err != nil {
return nil, err
}
case Content.URLEncoded:
var encs url.Values
encs, err = url.ParseQuery(string(b))
// normalize the http.Values type to flat map
for k, v := range encs {
body[k] = v[0]
}
// TODO: need to evalueate multipart form data
case Content.Multipart:
err := req.ParseMultipartForm(32 << 20)
if err != nil {
return nil, err
}
break
}
values := reflect.ValueOf(en)
fields := values.Elem().Type()
num := values.Elem().NumField()
for i := 0; i < num; i++ {
field := fields.Field(i)
if field.Name == "Entity" {
continue
}
tag := field.Tag.Get(rubikTag)
value := values.Elem().Field(i)
transport := "query"
transportKey := unCapitalize(field.Name)
isRequired := false
if strings.Contains(tag, "!") {
isRequired = true
tag = strings.ReplaceAll(tag, "!", "")
}
// get information from the tag
if tag != "" {
if strings.Contains(tag, "|") {
reqTag := strings.Split(tag, "|")
if reqTag[0] != "" {
transportKey = reqTag[0]
}
if reqTag[1] != "" {
transport = reqTag[1]
}
} else {
if isOneOf(tag, "query", "body", "form", "param") {
transport = tag
} else {
transportKey = tag
}
}
}
msg := "Data: %s is required but not found inside %s."
requiredError := errors.New(fmt.Sprintf(msg, transportKey, transport))
var val interface{}
switch transport {
case "query":
val = req.URL.Query().Get(transportKey)
if isRequired && (val == "" || val == nil) {
return nil, requiredError
}
break
case "body":
val = body[transportKey]
if (val == nil || val == "") && isRequired {
return nil, requiredError
}
break
case "form":
files := req.MultipartForm.File[transportKey]
if (files == nil || len(files) == 0) && isRequired {
return nil, requiredError
}
val = files
break
case "param":
paramKey := capitalize(strings.ToLower(transportKey))
val = params[paramKey]
if val == "" && isRequired {
return nil, requiredError
}
break
}
// this is for the validations the developer provieded
if len(v) > 0 && v[field.Name] != "" {
err := checker.Check(value, v[field.Name])
if err != nil {
return nil, err
}
}
injectValueByType(val, value, field.Type.Kind())
}
return en, nil
}
func injectValueByType(val interface{}, elem reflect.Value, typ reflect.Kind) {
switch typ {
case reflect.String:
final, ok := val.(string)
if ok && elem.CanSet() {
elem.SetString(final)
}
break
case reflect.Int:
value, _ := val.(string)
if value == "" {
return
}
final, ok := strconv.Atoi(value)
if ok == nil && elem.CanSet() {
elem.SetInt(int64(final))
}
break
case reflect.Float32:
value, _ := val.(string)
if value == "" {
return
}
// TODO: can make this conversion a function
if floatVal, err := strconv.ParseFloat(value, 32); err == nil && elem.CanSet() {
elem.SetFloat(floatVal)
}
break
case reflect.Float64:
value, _ := val.(string)
if value == "" {
return
}
// TODO: can make this conversion a function
if floatVal, err := strconv.ParseFloat(value, 64); err == nil && elem.CanSet() {
elem.SetFloat(floatVal)
}
break
case reflect.Bool:
value, _ := val.(string)
if value == "" {
return
}
boolean, err := strconv.ParseBool(value)
if err == nil && elem.CanSet() {
elem.SetBool(boolean)
}
break
case reflect.Struct:
// should we loop a on all struct fields and add value?
break
case reflect.Slice:
break
case reflect.TypeOf(File{}).Kind():
// if it is a single file we coece it into []multipart.File first and
// pick up the first one
value, ok := val.([]*multipart.File)
if ok && elem.CanSet() && len(value) > 0 {
file := *(value)[0]
defer file.Close()
b, err := ioutil.ReadAll(file)
if err != nil {
pkg.ErrorMsg("error while reading form file: " + err.Error())
return
}
elem.FieldByName("Raw").SetBytes(b)
}
break
case reflect.TypeOf([]File{}).Kind():
// TODO: the above File{} case and this can be a single function
value, ok := val.([]*multipart.File)
if ok && elem.CanSet() && len(value) > 0 {
for _, f := range value {
file := *f
defer file.Close()
b, err := ioutil.ReadAll(file)
if err != nil {
pkg.ErrorMsg("error while reading form file: " + err.Error())
return
}
sliceElem := reflect.MakeSlice(elem.Type(), len(value), elem.Cap())
for i := 0; i < len(value); i++ {
rubikFile := reflect.New(reflect.TypeOf(File{}))
rubikFile.FieldByName("Raw").SetBytes(b)
sliceElem.Index(i).Set(reflect.ValueOf(rubikFile).Elem())
}
}
}
break
}
}