-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathparser.go
354 lines (308 loc) · 8.51 KB
/
parser.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package gongular
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/asaskevich/govalidator"
)
const (
// PlaceParameter is used in ValidationError to indicate the error is in
// URL Parameters
PlaceParameter = "URL Path Parameter"
// PlaceQuery is used in ValidationError to indicate the error is in
// Query parameters
PlaceQuery = "Query Parameter"
// PlaceBody is used in ValidationError to indicate the error is in
// Body of the request
PlaceBody = "Body"
// PlaceForm is used in ValidationError to indicate the error is in
// submitted form
PlaceForm = "Form Value"
)
const (
// FieldParameter defines the struct field name for looking up URL Parameters
FieldParameter = "Param"
// FieldBody defines the struct field name for looking up the body of request
FieldBody = "Body"
// FieldForm defines the struct field name for looking up form of request
FieldForm = "Form"
// FieldQuery defines the struct field name for looking up QUery Parameters
FieldQuery = "Query"
)
const (
// TagInject The field name that is used to lookup injections in the handlers
TagInject = "inject"
// TagQuery is the field tag to define a query parameter's key
TagQuery = "q"
)
var (
errUnassignable = errors.New("value is not assignable to this type")
)
func parseInt(kind reflect.Kind, s string, place string, field reflect.StructField, val *reflect.Value) error {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return ParseError{
Place: place,
FieldName: field.Name,
Reason: fmt.Sprintf("The '%s' is not parseable to a integer", s),
}
}
ok, lower, upper := checkIntRange(kind, i)
if !ok {
return ParseError{
Place: place,
FieldName: field.Name,
Reason: fmt.Sprintf("Supplied value %d is not in range [%d, %d]", i, lower, upper),
}
}
val.SetInt(i)
return nil
}
func parseUint(kind reflect.Kind, s string, place string, field reflect.StructField, val *reflect.Value) error {
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return ParseError{
Place: place,
FieldName: field.Name,
Reason: fmt.Sprintf("The '%s' is not parseable to int", s),
}
}
ok, lower, upper := checkUIntRange(kind, i)
if !ok {
return ParseError{
Place: place,
FieldName: field.Name,
Reason: fmt.Sprintf("Supplied value %d is not in range [%d, %d]", i, lower, upper),
}
}
val.SetUint(i)
return nil
}
func parseFloat(kind reflect.Kind, s string, place string, field reflect.StructField, val *reflect.Value) error {
i, err := strconv.ParseFloat(s, 64)
if err != nil {
return ParseError{
Place: place,
FieldName: field.Name,
Reason: fmt.Sprintf("The '%s' is not parseable to float/double", s),
}
}
ok, lower, upper := checkFloatRange(kind, i)
if !ok {
return ParseError{
Place: place,
FieldName: field.Name,
Reason: fmt.Sprintf("Supplied value %f is not in range [%f, %f]", i, lower, upper),
}
}
val.SetFloat(i)
return nil
}
func parseBool(s string, place string, field reflect.StructField, val *reflect.Value) error {
switch strings.ToLower(s) {
case "true", "1", "yes":
val.SetBool(true)
case "false", "0", "no":
val.SetBool(false)
default:
return ParseError{
FieldName: field.Name,
Place: place,
Reason: fmt.Sprintf("The '%s' is not a boolean", s),
}
}
return nil
}
func parseSimpleParam(s string, place string, field reflect.StructField, val *reflect.Value) error {
kind := field.Type.Kind()
var err error
switch kind {
case reflect.String:
val.SetString(s)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = parseInt(kind, s, place, field, val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
err = parseUint(kind, s, place, field, val)
case reflect.Float32, reflect.Float64:
err = parseFloat(kind, s, place, field, val)
case reflect.Bool:
err = parseBool(s, place, field, val)
}
return err
}
func validateStruct(obj reflect.Value, place string) error {
isValid, err := govalidator.ValidateStruct(obj.Interface())
if !isValid {
m := govalidator.ErrorsByField(err)
return ValidationError{
Place: place,
Fields: m,
}
}
return nil
}
func (c *Context) parseParams(obj reflect.Value) error {
param := obj.FieldByName(FieldParameter)
paramType := param.Type()
numFields := paramType.NumField()
for i := 0; i < numFields; i++ {
field := paramType.Field(i)
s := c.Params().ByName(field.Name)
val := param.Field(i)
err := parseSimpleParam(s, PlaceParameter, field, &val)
if err != nil {
return err
}
}
return validateStruct(param, PlaceParameter)
}
func (c *Context) parseBody(handlerObject reflect.Value) error {
// TODO: Cache body if possible?
body := handlerObject.FieldByName(FieldBody)
b := body.Addr().Interface()
err := json.NewDecoder(c.Request().Body).Decode(b)
if err != nil {
return ParseError{
Place: PlaceBody,
Reason: err.Error(),
}
}
return validateStruct(body, PlaceBody)
}
func (c *Context) parseQuery(obj reflect.Value) error {
query := obj.FieldByName(FieldQuery)
queryType := query.Type()
numFields := queryType.NumField()
queryValues := c.Request().URL.Query()
for i := 0; i < numFields; i++ {
field := queryType.Field(i)
var s string
tag, ok := field.Tag.Lookup(TagQuery)
if ok {
s = queryValues.Get(tag)
} else {
s = queryValues.Get(field.Name)
}
if s == "" {
// Do not fail right now, it is the job of validator
continue
}
val := query.Field(i)
err := parseSimpleParam(s, PlaceQuery, field, &val)
if err != nil {
return err
}
}
return validateStruct(query, PlaceQuery)
}
func (c *Context) parseForm(obj reflect.Value) error {
form := obj.FieldByName(FieldForm)
formType := form.Type()
numFields := formType.NumField()
for i := 0; i < numFields; i++ {
field := formType.Field(i)
// If it is a file, parse the form
if field.Type == reflect.TypeOf(&UploadedFile{}) {
file, header, err := c.Request().FormFile(field.Name)
// TODO: Make it optional??
if err == http.ErrMissingFile {
return ParseError{
Place: PlaceForm,
FieldName: field.Name,
Reason: "Was expecting a file, but could not found in the request.",
}
} else if err != nil {
// It should be an internal error, therefore we do not wrap with ParseError
return err
}
// Pack them to a single structure
uploadedFile := &UploadedFile{
File: file,
Header: header,
}
form.Field(i).Set(reflect.ValueOf(uploadedFile))
} else {
s := c.Request().FormValue(field.Name)
val := form.Field(i)
err := parseSimpleParam(s, PlaceForm, field, &val)
if err != nil {
return err
}
}
}
return validateStruct(form, PlaceForm)
}
func (c *Context) parseInjections(obj reflect.Value, injector *injector) error {
numFields := obj.Type().NumField()
for i := 0; i < numFields; i++ {
field := obj.Type().Field(i)
tip := field.Type
name := field.Name
// We can skip the field if it is a special one
if name == FieldBody || name == FieldParameter || name == FieldQuery || name == FieldForm {
continue
}
if !obj.Field(i).CanSet() {
// It is an un-exported one
continue
}
var key string
tag, ok := field.Tag.Lookup(TagInject)
if !ok {
key = "default"
} else {
key = tag
}
fieldObj := obj.Field(i)
err := c.setInjectionForField(tip, key, injector, fieldObj)
if err != nil {
return err
}
}
return nil
}
func (c *Context) setInjectionForField(tip reflect.Type, key string, injector *injector, fieldObj reflect.Value) error {
cachedVal, cachedOk := c.getCachedInjection(tip, key)
val, directOk := injector.GetDirectValue(tip, key)
fn, customOk := injector.GetCustomValue(tip, key)
uval, uvalOK := injector.GetUnsafeValue(key)
if uvalOK {
if !uval.Type().AssignableTo(tip) {
return InjectionError{
Key: key,
Tip: tip,
UnderlyingError: errUnassignable,
}
}
fieldObj.Set(uval)
return nil
} else if cachedOk {
fieldObj.Set(reflect.ValueOf(cachedVal))
return nil
} else if directOk {
fieldObj.Set(reflect.ValueOf(val))
return nil
} else if customOk {
val, err := fn(c)
if err != nil {
return InjectionError{
Key: key,
Tip: tip,
UnderlyingError: err,
}
}
fieldObj.Set(reflect.ValueOf(val))
c.putCachedInjection(tip, key, val)
return nil
}
// We should not be here if the programmatic check is done correctly, but placed it here anyways
return InjectionError{
Key: key,
Tip: tip,
UnderlyingError: ErrNoSuchDependency,
}
}