-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault_binder.go
410 lines (362 loc) · 13.4 KB
/
default_binder.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package binder
import (
"errors"
"mime/multipart"
"net/url"
"reflect"
"regexp"
"strings"
)
// DefaultBinder is the default implementation of the `Binder` interface.
type DefaultBinder struct {
JSONSerializer JSONSerializer
XMLSerializer XMLSerializer
PathMatcher *regexp.Regexp
ArrayMatcher *regexp.Regexp
MapMatcher *regexp.Regexp
ArrayNotationMatcher *regexp.Regexp
DeepObjectSeparator string
MaxBodySize int64
MaxArraySize int
HeaderTagName string
FormTagName string
QueryTagName string
ParamTagName string
BindOrder []BindFunc
}
func NewBinder() *DefaultBinder {
r := &DefaultBinder{
JSONSerializer: DefaultJSONSerializer{},
XMLSerializer: DefaultXMLSerializer{},
PathMatcher: PathMatcherRegexp,
MaxBodySize: DefaultBodySize,
MapMatcher: MapMatcherRegexp,
ArrayMatcher: ArrayMatcherRegexp,
ArrayNotationMatcher: ArrayNotationRegexp,
MaxArraySize: MaxArraySize,
HeaderTagName: DefaultHeaderTagName,
FormTagName: DefaultFormTagName,
QueryTagName: DefaultQueryTagName,
ParamTagName: DefaultParamTagName,
DeepObjectSeparator: DefaultDeepObjectSeparator,
BindOrder: []BindFunc{},
}
r.BindOrder = []BindFunc{
r.BindPathParams,
r.BindQueryParams,
r.BindBody,
}
return r
}
func (b *DefaultBinder) GetPathParams(r BindableRequest) map[string][]string {
pattern := r.GetPathPattern()
if pattern == "" {
return nil
}
names := b.PathMatcher.FindAllStringSubmatch(pattern, -1)
if len(names) == 0 {
return nil
}
values := map[string][]string{}
for _, name := range names {
values[name[1]] = []string{r.GetPathValue(name[1])}
}
return values
}
func (b *DefaultBinder) GetQueryParams(r BindableRequest) map[string][]string {
return r.GetQuery()
}
func (b *DefaultBinder) GetHeaders(r BindableRequest) map[string][]string {
return r.GetHeaders()
}
// BindPathParams binds path params to bindable object
func (b *DefaultBinder) BindPathParams(r BindableRequest, i interface{}) error {
values := b.GetPathParams(r)
if err := b.bindData(i, values, b.ParamTagName, nil); err != nil {
return err
}
return nil
}
// BindQueryParams binds query params to bindable object
func (b *DefaultBinder) BindQueryParams(r BindableRequest, i interface{}) error {
values := b.GetQueryParams(r)
if err := b.bindData(i, values, b.QueryTagName, nil); err != nil {
return err
}
return nil
}
// BindBody binds request body contents to bindable object
// NB: then binding forms take note that this implementation uses standard library form parsing
// which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm
// See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm
// See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm
func (b *DefaultBinder) BindBody(r BindableRequest, i interface{}) (err error) {
if r.GetContentLength() <= 0 {
return
}
// return
// mediatype is found like `mime.ParseMediaType()` does it
base, _, _ := strings.Cut(r.GetHeaders().Get(HeaderContentType), ";")
mediatype := strings.TrimSpace(base)
switch mediatype {
case MIMEApplicationJSON:
if err = b.JSONSerializer.Deserialize(r, i); err != nil {
return err
}
case MIMEApplicationXML, MIMETextXML:
if err = b.XMLSerializer.Deserialize(r, i); err != nil {
return err
}
case MIMEApplicationForm:
var form url.Values
if form, err = r.GetForm(); err != nil {
return err
}
if err = b.bindData(i, form, b.FormTagName, nil); err != nil {
return err
}
case MIMEMultipartForm:
var params *multipart.Form
if params, err = r.GetMultipartForm(b.MaxBodySize); err != nil {
return err
}
if err = b.bindData(i, params.Value, b.FormTagName, params.File); err != nil {
return err
}
default:
return errors.New("unsupported media type")
}
return nil
}
// BindHeaders binds HTTP headers to a bindable object
func (b *DefaultBinder) BindHeaders(r BindableRequest, i interface{}) error {
if err := b.bindData(i, r.GetHeaders(), b.FormTagName, nil); err != nil {
return err
}
return nil
}
// Bind implements the `Binder#Bind` function.
// Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous
// step binded values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams.
func (b *DefaultBinder) Bind(r BindableRequest, i interface{}) (err error) {
for _, bindFunc := range b.BindOrder {
if err = bindFunc(r, i); err != nil {
return err
}
}
return nil
}
// bindData will bind data ONLY fields in destination struct that have EXPLICIT tag
func (b *DefaultBinder) bindData(destination interface{}, data map[string][]string, tag string, dataFiles map[string][]*multipart.FileHeader) error {
if destination == nil || (len(data) == 0 && len(dataFiles) == 0) {
return nil
}
hasFiles := len(dataFiles) > 0
typ := reflect.TypeOf(destination).Elem()
val := reflect.ValueOf(destination).Elem()
// Support binding to limited Map destinations:
// - map[string][]string,
// - map[string]string <-- (binds first value from data slice)
// - map[string]interface{}
// You are better off binding to struct but there are user who want this map feature. Source of data for these cases are:
// params,query,header,form as these sources produce string values, most of the time slice of strings, actually.
if typ.Kind() == reflect.Map && typ.Key().Kind() == reflect.String {
k := typ.Elem().Kind()
isElemInterface := k == reflect.Interface
isElemString := k == reflect.String
isElemSliceOfStrings := k == reflect.Slice && typ.Elem().Elem().Kind() == reflect.String
if !(isElemSliceOfStrings || isElemString || isElemInterface) {
return nil
}
if val.IsNil() {
val.Set(reflect.MakeMap(typ))
}
for k, v := range data {
if isElemString {
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0]))
} else if isElemInterface {
// To maintain backward compatibility, we always bind to the first string value
// and not the slice of strings when dealing with map[string]interface{}{}
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0]))
} else {
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v))
}
}
return nil
}
// !struct
if typ.Kind() != reflect.Struct && typ.Kind() != reflect.Ptr {
if tag == b.ParamTagName || tag == b.QueryTagName || tag == b.HeaderTagName {
// incompatible type, data is probably to be found in the body
return nil
}
return errors.New("binding element must be a struct")
}
// deference struct
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
val = val.Elem()
}
for i := 0; i < typ.NumField(); i++ { // iterate over all destination fields
typeField := typ.Field(i)
structField := val.Field(i)
if typeField.Anonymous {
if structField.Kind() == reflect.Ptr {
structField = structField.Elem()
}
}
if !structField.CanSet() {
continue
}
structFieldKind := structField.Kind()
inputFieldName := typeField.Tag.Get(tag)
if typeField.Anonymous && structFieldKind == reflect.Struct && inputFieldName != "" {
// if anonymous struct with query/param/form tags, report an error
return errors.New("query/param/form tags are not allowed with anonymous struct field")
}
if inputFieldName == "" {
// If tag is nil, we inspect if the field is a not BindUnmarshaler struct and try to bind data into it (might contain fields with tags).
// structs that implement BindUnmarshaler are bound only when they have explicit tag
if _, ok := structField.Addr().Interface().(BindUnmarshaler); !ok && structFieldKind == reflect.Struct {
if err := b.bindData(structField.Addr().Interface(), data, tag, dataFiles); err != nil {
return err
}
}
// does not have explicit tag and is not an ordinary struct - so move to next field
continue
}
if hasFiles {
if ok, err := isFieldMultipartFile(structField.Type()); err != nil {
return err
} else if ok {
if ok := setMultipartFileHeaderTypes(structField, inputFieldName, dataFiles); ok {
continue
}
}
}
//if the field is a struct, we need to recursively bind data to it
if structFieldKind == reflect.Struct {
// the data now is only the data that is relevant to the current struct
structData := trimData(inputFieldName, data, b.ArrayNotationMatcher, b.DeepObjectSeparator)
structFiles := trimFileFields(inputFieldName, dataFiles, b.ArrayNotationMatcher, b.DeepObjectSeparator)
if err := b.bindData(structField.Addr().Interface(), structData, tag, structFiles); err != nil {
return err
}
continue
} else if structFieldKind == reflect.Map {
// the data now is only the data that is relevant to the current field
mapData := trimData(inputFieldName, data, b.MapMatcher, b.DeepObjectSeparator)
mapFiles := trimFileFields(inputFieldName, dataFiles, b.MapMatcher, b.DeepObjectSeparator)
if err := b.bindData(structField.Addr().Interface(), mapData, tag, mapFiles); err != nil {
return err
}
// continue
} else if structFieldKind == reflect.Slice {
// the data now is only the data that is relevant to the current field
sliceData := trimData(inputFieldName, data, b.ArrayMatcher, b.DeepObjectSeparator)
sliceFiles := trimFileFields(inputFieldName, dataFiles, b.ArrayMatcher, b.DeepObjectSeparator)
if err := handleArrayValues(structField, structFieldKind, sliceData, sliceFiles, inputFieldName, b.MaxArraySize); err != nil {
return err
}
}
inputValue, exists := data[inputFieldName]
if !exists {
// Go json.Unmarshal supports case-insensitive binding. However the
// url params are bound case-sensitive which is inconsistent. To
// fix this we must check all of the map values in a
// case-insensitive search.
for k, v := range data {
if strings.EqualFold(k, inputFieldName) {
inputValue = v
exists = true
break
}
}
}
if !exists {
if structFieldKind == reflect.Ptr { // if the field is a pointer, we need to check if it is a struct
elem := typeField.Type.Elem() // get the type of the pointer
valueKind := elem.Kind()
if valueKind == reflect.Struct {
structData := trimData(inputFieldName, data, b.ArrayNotationMatcher, b.DeepObjectSeparator)
structFiles := trimFileFields(inputFieldName, dataFiles, b.ArrayNotationMatcher, b.DeepObjectSeparator)
if len(structData) == 0 && len(structFiles) == 0 { // no data for this field
continue
}
if structField.IsNil() {
structField.Set(reflect.New(structField.Type().Elem()))
}
// fmt.Println("structFiles", structFiles)
if err := b.bindData(structField.Addr().Interface(), structData, tag, structFiles); err != nil {
return err
}
continue
} else if valueKind == reflect.Slice {
// the data now is only the data that is relevant to the current field
sliceData := trimData(inputFieldName, data, b.ArrayMatcher, b.DeepObjectSeparator)
sliceFiles := trimFileFields(inputFieldName, dataFiles, b.ArrayMatcher, b.DeepObjectSeparator)
if len(sliceData) == 0 && len(sliceFiles) == 0 { // no data for this field
continue
}
if structField.IsNil() {
structField.Set(reflect.New(structField.Type().Elem()))
}
if err := handleArrayValues(structField, structFieldKind, sliceData, sliceFiles, inputFieldName, b.MaxArraySize); err != nil {
return err
}
} else if valueKind == reflect.Map {
// the data now is only the data that is relevant to the current field
mapData := trimData(inputFieldName, data, b.MapMatcher, b.DeepObjectSeparator)
mapFiles := trimFileFields(inputFieldName, dataFiles, b.MapMatcher, b.DeepObjectSeparator)
if len(mapData) == 0 && len(mapFiles) == 0 { // no data for this field
continue
}
if structField.IsNil() {
structField.Set(reflect.New(structField.Type().Elem()))
}
if err := b.bindData(structField.Interface(), mapData, tag, mapFiles); err != nil {
return err
}
}
}
continue
}
// NOTE: algorithm here is not particularly sophisticated. It probably does not work with absurd types like `**[]*int`
// but it is smart enough to handle niche cases like `*int`,`*[]string`,`[]*int` .
// try unmarshalling first, in case we're dealing with an alias to an array type
if ok, err := unmarshalInputsToField(typeField.Type.Kind(), inputValue, structField); ok {
if err != nil {
return err
}
continue
}
if ok, err := unmarshalInputToField(typeField.Type.Kind(), inputValue[0], structField); ok {
if err != nil {
return err
}
continue
}
// we could be dealing with pointer to slice `*[]string` so dereference it. There are wierd OpenAPI generators
// that could create struct fields like that.
if structFieldKind == reflect.Pointer {
structFieldKind = structField.Elem().Kind()
structField = structField.Elem()
}
if structFieldKind == reflect.Slice {
sliceOf := structField.Type().Elem().Kind()
numElems := len(inputValue)
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for j := 0; j < numElems; j++ {
if err := setWithProperType(sliceOf, inputValue[j], slice.Index(j)); err != nil {
return err
}
}
structField.Set(slice)
continue
}
if err := setWithProperType(structFieldKind, inputValue[0], structField); err != nil {
return err
}
}
return nil
}