Repository navigation
Expand file tree
/
Copy pathbindform.go
More file actions
560 lines (533 loc) · 16.2 KB
/
Copy pathbindform.go
File metadata and controls
560 lines (533 loc) · 16.2 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package runtime
import (
"bytes"
"encoding"
"encoding/json"
"errors"
"fmt"
"mime/multipart"
"net/url"
"reflect"
"strconv"
"strings"
"github.com/oapi-codegen/runtime/types"
)
const jsonTagName = "json"
const formTagName = "form"
const jsonContentType = "application/json"
// formFieldTag returns the struct tag value that names a field on the wire
// for form encoding. The `form` tag is preferred when present and non-empty;
// the `json` tag is the historical fallback, kept for compatibility with
// generated and hand-written structs that carry only json tags. The full tag
// value is returned, so `-` skips and the `,omitempty` option follow
// whichever tag was selected.
func formFieldTag(f reflect.StructField) string {
if tag, ok := f.Tag.Lookup(formTagName); ok && tag != "" {
return tag
}
return f.Tag.Get(jsonTagName)
}
type RequestBodyEncoding struct {
ContentType string
Style string
Explode *bool
Required *bool
}
func BindMultipart(ptr interface{}, reader multipart.Reader) error {
const defaultMemory = 32 << 20
form, err := reader.ReadForm(defaultMemory)
if err != nil {
return err
}
return BindForm(ptr, form.Value, form.File, nil)
}
func BindForm(ptr interface{}, form map[string][]string, files map[string][]*multipart.FileHeader, encodings map[string]RequestBodyEncoding) error {
ptrVal := reflect.Indirect(reflect.ValueOf(ptr))
if ptrVal.Kind() != reflect.Struct {
return errors.New("form data body should be a struct")
}
tValue := ptrVal.Type()
for i := 0; i < tValue.NumField(); i++ {
field := ptrVal.Field(i)
tag := formFieldTag(tValue.Field(i))
if !field.CanInterface() || tag == "-" {
continue
}
tag = strings.Split(tag, ",")[0] // extract the name of the tag
if encoding, ok := encodings[tag]; ok {
// custom encoding
values := form[tag]
if len(values) == 0 {
continue
}
value := values[0]
if encoding.ContentType != "" {
if strings.HasPrefix(encoding.ContentType, jsonContentType) {
if err := JSONUnmarshal([]byte(value), ptr); err != nil {
return err
}
}
return errors.New("unsupported encoding, only application/json is supported")
} else {
var explode bool
if encoding.Explode != nil {
explode = *encoding.Explode
}
var required bool
if encoding.Required != nil {
required = *encoding.Required
}
if err := BindStyledParameterWithOptions(encoding.Style, tag, value, field.Addr().Interface(), BindStyledParameterOptions{
ParamLocation: ParamLocationUndefined,
Explode: explode,
Required: required,
}); err != nil {
return err
}
}
} else {
// regular form data
if _, err := bindFormImpl(field, form, files, tag); err != nil {
return err
}
}
}
return nil
}
// MarshalForm serializes a struct into application/x-www-form-urlencoded
// values.
//
// Properties are written in bracketed form by default: an array becomes
// name[0]=a&name[1]=b and a nested object becomes name[key]=value. A property
// with an entry in encodings follows that entry instead, mirroring the OpenAPI
// Encoding Object:
//
// - ContentType: the value is serialized as a single field in that media
// type. Only application/json is supported.
// - Style and Explode: arrays and flat objects are serialized as a query
// parameter of that style would be. "form" (the default when only Explode
// is set), "spaceDelimited" and "pipeDelimited" write repeated keys
// (name=a&name=b) when exploded and one delimited value (name=a,b)
// otherwise; "deepObject" is the bracketed default. Explode defaults to
// true for "form" and false for the other styles, as in the specification.
//
// An entry which sets none of those leaves the default in place.
func MarshalForm(ptr interface{}, encodings map[string]RequestBodyEncoding) (url.Values, error) {
ptrVal := reflect.Indirect(reflect.ValueOf(ptr))
if ptrVal.Kind() != reflect.Struct {
return nil, errors.New("form data body should be a struct")
}
tValue := ptrVal.Type()
result := make(url.Values)
for i := 0; i < tValue.NumField(); i++ {
field := ptrVal.Field(i)
tag := formFieldTag(tValue.Field(i))
if !field.CanInterface() || tag == "-" {
continue
}
omitEmpty := strings.HasSuffix(tag, ",omitempty")
if omitEmpty && field.IsZero() {
continue
}
tag = strings.Split(tag, ",")[0] // extract the name of the tag
encoding, hasEncoding := encodings[tag]
switch {
case hasEncoding && encoding.ContentType != "":
if !strings.HasPrefix(encoding.ContentType, jsonContentType) {
return nil, errors.New("unsupported encoding, only application/json is supported")
}
if (field.Kind() == reflect.Pointer || field.Kind() == reflect.Interface) && field.IsNil() {
continue
}
data, err := JSONMarshal(field.Interface())
if err != nil {
return nil, err
}
result[tag] = append(result[tag], string(data))
case hasEncoding && (encoding.Style != "" || encoding.Explode != nil):
if err := marshalFormStyled(field, result, tag, encoding); err != nil {
return nil, err
}
default:
marshalFormImpl(field, result, tag)
}
}
return result, nil
}
func bindFormImpl(v reflect.Value, form map[string][]string, files map[string][]*multipart.FileHeader, name string) (bool, error) {
var hasData bool
switch v.Kind() {
case reflect.Interface:
return bindFormImpl(v.Elem(), form, files, name)
case reflect.Pointer:
ptrData := v.Elem()
if !ptrData.IsValid() {
ptrData = reflect.New(v.Type().Elem())
}
ptrHasData, err := bindFormImpl(ptrData, form, files, name)
if err == nil && ptrHasData && !v.Elem().IsValid() {
v.Set(ptrData)
}
return ptrHasData, err
case reflect.Slice:
if files := append(files[name], files[name+"[]"]...); len(files) != 0 {
if _, ok := v.Interface().([]types.File); ok {
result := make([]types.File, len(files))
for i, file := range files {
result[i].InitFromMultipart(file)
}
v.Set(reflect.ValueOf(result))
hasData = true
}
}
indexedElementsCount := indexedElementsCount(form, files, name)
items := append(form[name], form[name+"[]"]...)
if indexedElementsCount+len(items) != 0 {
result := reflect.MakeSlice(v.Type(), indexedElementsCount+len(items), indexedElementsCount+len(items))
for i := 0; i < indexedElementsCount; i++ {
if _, err := bindFormImpl(result.Index(i), form, files, fmt.Sprintf("%s[%v]", name, i)); err != nil {
return false, err
}
}
for i, item := range items {
if err := BindStringToObject(item, result.Index(indexedElementsCount+i).Addr().Interface()); err != nil {
return false, err
}
}
v.Set(result)
hasData = true
}
case reflect.Struct:
if files := files[name]; len(files) != 0 {
if file, ok := v.Interface().(types.File); ok {
file.InitFromMultipart(files[0])
v.Set(reflect.ValueOf(file))
return true, nil
}
}
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i)
tag := formFieldTag(field)
if field.Name == "AdditionalProperties" && field.Type.Kind() == reflect.Map && tag == "-" {
additionalPropertiesHasData, err := bindAdditionalProperties(v.Field(i), v, form, files, name)
if err != nil {
return false, err
}
hasData = hasData || additionalPropertiesHasData
}
if !v.Field(i).CanInterface() || tag == "-" {
continue
}
tag = strings.Split(tag, ",")[0] // extract the name of the tag
fieldHasData, err := bindFormImpl(v.Field(i), form, files, fmt.Sprintf("%s[%s]", name, tag))
if err != nil {
return false, err
}
hasData = hasData || fieldHasData
}
return hasData, nil
case reflect.Map:
// A bool-keyed map (such as nullable.Nullable[T], which is
// map[bool]T) is treated as a nullable wrapper: bind the inner type
// and store the result under map[true]. An absent field stays as
// the zero (unspecified) map.
if v.Type().Key().Kind() == reflect.Bool {
valuePtr := reflect.New(v.Type().Elem())
valueHasData, err := bindFormImpl(valuePtr.Elem(), form, files, name)
if err != nil {
return false, err
}
if valueHasData {
newMap := reflect.MakeMap(v.Type())
newMap.SetMapIndex(reflect.ValueOf(true), valuePtr.Elem())
v.Set(newMap)
return true, nil
}
return false, nil
}
return bindFormMap(v, form, files, name)
default:
value := form[name]
if len(value) != 0 {
return true, BindStringToObject(value[0], v.Addr().Interface())
}
}
return hasData, nil
}
func indexedElementsCount(form map[string][]string, files map[string][]*multipart.FileHeader, name string) int {
name += "["
maxIndex := -1
for k := range form {
if strings.HasPrefix(k, name) {
str := strings.TrimPrefix(k, name)
str = str[:strings.Index(str, "]")]
if idx, err := strconv.Atoi(str); err == nil {
if idx > maxIndex {
maxIndex = idx
}
}
}
}
for k := range files {
if strings.HasPrefix(k, name) {
str := strings.TrimPrefix(k, name)
str = str[:strings.Index(str, "]")]
if idx, err := strconv.Atoi(str); err == nil {
if idx > maxIndex {
maxIndex = idx
}
}
}
}
return maxIndex + 1
}
func bindAdditionalProperties(additionalProperties reflect.Value, parentStruct reflect.Value, form map[string][]string, files map[string][]*multipart.FileHeader, name string) (bool, error) {
hasData := false
valueType := additionalProperties.Type().Elem()
// store all fixed properties in a set
fieldsSet := make(map[string]struct{})
for i := 0; i < parentStruct.NumField(); i++ {
tag := formFieldTag(parentStruct.Type().Field(i))
if !parentStruct.Field(i).CanInterface() || tag == "-" {
continue
}
tag = strings.Split(tag, ",")[0]
fieldsSet[tag] = struct{}{}
}
result := reflect.MakeMap(additionalProperties.Type())
for k := range form {
if strings.HasPrefix(k, name+"[") {
key := strings.TrimPrefix(k, name+"[")
key = key[:strings.Index(key, "]")]
if _, ok := fieldsSet[key]; ok {
continue
}
value := reflect.New(valueType)
ptrHasData, err := bindFormImpl(value, form, files, fmt.Sprintf("%s[%s]", name, key))
if err != nil {
return false, err
}
result.SetMapIndex(reflect.ValueOf(key), value.Elem())
hasData = hasData || ptrHasData
}
}
for k := range files {
if strings.HasPrefix(k, name+"[") {
key := strings.TrimPrefix(k, name+"[")
key = key[:strings.Index(key, "]")]
if _, ok := fieldsSet[key]; ok {
continue
}
value := reflect.New(valueType)
result.SetMapIndex(reflect.ValueOf(key), value)
ptrHasData, err := bindFormImpl(value, form, files, fmt.Sprintf("%s[%s]", name, key))
if err != nil {
return false, err
}
result.SetMapIndex(reflect.ValueOf(key), value.Elem())
hasData = hasData || ptrHasData
}
}
if hasData {
additionalProperties.Set(result)
}
return hasData, nil
}
// bindFormMap binds form (and file) entries of the form `name[key]=value`
// into a generic map[K]V destination. It is reached from bindFormImpl for
// non-bool-keyed maps; the bool-keyed case is handled separately as a
// nullable wrapper.
func bindFormMap(v reflect.Value, form map[string][]string, files map[string][]*multipart.FileHeader, name string) (bool, error) {
keyType := v.Type().Key()
valueType := v.Type().Elem()
result := reflect.MakeMap(v.Type())
hasData := false
prefix := name + "["
seen := map[string]struct{}{}
process := func(formKey string) error {
if !strings.HasPrefix(formKey, prefix) {
return nil
}
inner := strings.TrimPrefix(formKey, prefix)
end := strings.Index(inner, "]")
if end < 0 {
return nil
}
innerKey := inner[:end]
if _, ok := seen[innerKey]; ok {
return nil
}
seen[innerKey] = struct{}{}
keyPtr := reflect.New(keyType)
if err := BindStringToObject(innerKey, keyPtr.Interface()); err != nil {
return err
}
valuePtr := reflect.New(valueType)
innerHasData, err := bindFormImpl(valuePtr.Elem(), form, files, fmt.Sprintf("%s[%s]", name, innerKey))
if err != nil {
return err
}
if innerHasData {
result.SetMapIndex(keyPtr.Elem(), valuePtr.Elem())
hasData = true
}
return nil
}
for k := range form {
if err := process(k); err != nil {
return false, err
}
}
for k := range files {
if err := process(k); err != nil {
return false, err
}
}
if hasData {
v.Set(result)
}
return hasData, nil
}
func marshalFormImpl(v reflect.Value, result url.Values, name string) {
switch v.Kind() {
case reflect.Pointer:
if v.IsNil() {
break
}
fallthrough
case reflect.Interface:
marshalFormImpl(v.Elem(), result, name)
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
elem := v.Index(i)
marshalFormImpl(elem, result, fmt.Sprintf("%s[%v]", name, i))
}
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i)
tag := formFieldTag(field)
if field.Name == "AdditionalProperties" && tag == "-" {
iter := v.MapRange()
for iter.Next() {
marshalFormImpl(iter.Value(), result, fmt.Sprintf("%s[%s]", name, iter.Key().String()))
}
continue
}
if !v.Field(i).CanInterface() || tag == "-" {
continue
}
tag = strings.Split(tag, ",")[0] // extract the name of the tag
marshalFormImpl(v.Field(i), result, fmt.Sprintf("%s[%s]", name, tag))
}
default:
result[name] = append(result[name], fmt.Sprint(v.Interface()))
}
}
// marshalFormStyled writes one top-level property according to the style and
// explode of its encoding. See MarshalForm.
func marshalFormStyled(v reflect.Value, result url.Values, name string, enc RequestBodyEncoding) error {
style := enc.Style
if style == "" {
style = "form"
}
explode := style == "form"
if enc.Explode != nil {
explode = *enc.Explode
}
var separator string
switch style {
case "form":
separator = ","
case "spaceDelimited":
separator = " "
case "pipeDelimited":
separator = "|"
case "deepObject":
// The bracketed default is the deepObject serialization.
marshalFormImpl(v, result, name)
return nil
default:
return fmt.Errorf("unsupported style '%s' for form property '%s'", style, name)
}
for v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface {
if v.IsNil() {
return nil
}
v = v.Elem()
}
value := v.Interface()
// Types which serialize to a single string are primitives, whatever
// their kind.
if str, ok := marshalKnownTypes(value); ok {
result[name] = append(result[name], str)
return nil
}
if tm, ok := value.(encoding.TextMarshaler); ok {
b, err := tm.MarshalText()
if err != nil {
return fmt.Errorf("error marshaling '%s' as text: %w", name, err)
}
result[name] = append(result[name], string(b))
return nil
}
var fieldDict map[string]string
var err error
switch v.Kind() {
case reflect.Slice:
parts := make([]string, v.Len())
for i := range parts {
if parts[i], err = primitiveToString(v.Index(i).Interface()); err != nil {
return fmt.Errorf("error formatting '%s': %w", name, err)
}
}
if explode {
result[name] = append(result[name], parts...)
} else {
result[name] = append(result[name], strings.Join(parts, separator))
}
return nil
case reflect.Struct:
// A struct with a Marshaler, such as one with additional properties,
// is styled from its JSON form.
if m, ok := value.(json.Marshaler); ok {
buf, err := m.MarshalJSON()
if err != nil {
return fmt.Errorf("failed to marshal '%s' to JSON: %w", name, err)
}
d := json.NewDecoder(bytes.NewReader(buf))
d.UseNumber()
var decoded interface{}
if err := d.Decode(&decoded); err != nil {
return fmt.Errorf("failed to unmarshal JSON for '%s': %w", name, err)
}
return marshalFormStyled(reflect.ValueOf(&decoded).Elem(), result, name, enc)
}
fieldDict, err = structFieldDict(name, value)
case reflect.Map:
fieldDict, err = mapFieldDict(name, value)
default:
str, err := primitiveToString(value)
if err != nil {
return fmt.Errorf("error formatting '%s': %w", name, err)
}
result[name] = append(result[name], str)
return nil
}
if err != nil {
return err
}
// An exploded object contributes each property as a field of its own.
keys := sortedKeys(fieldDict)
if explode {
for _, k := range keys {
result[k] = append(result[k], fieldDict[k])
}
return nil
}
parts := make([]string, 0, 2*len(keys))
for _, k := range keys {
parts = append(parts, k, fieldDict[k])
}
result[name] = append(result[name], strings.Join(parts, separator))
return nil
}