-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfield.go
More file actions
503 lines (465 loc) · 13.1 KB
/
field.go
File metadata and controls
503 lines (465 loc) · 13.1 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
package puff
import (
"encoding/json"
"fmt"
"log/slog"
"reflect"
"strconv"
"strings"
)
// FIXME: allow for example values
// isValidKind takes in specified_kind and returns
// if it is a supported and valid kind
func isValidKind(specified_kind string) bool {
// https://swagger.io/specification/#:~:text=the%20in%20property.-,in,query%22%2C%20%22header%22%2C%20%22path%22%20or%20%22cookie%22.,-description
return specified_kind == "header" ||
specified_kind == "path" ||
specified_kind == "query" ||
specified_kind == "cookie" ||
specified_kind == "body" ||
specified_kind == "form" ||
specified_kind == "file"
}
// TODO: i dont see this being used anywhere.
func enforceKindTypes(specifiedKind string, t reflect.Type) error {
switch specifiedKind {
case "header", "path", "query", "cookie":
switch t.Kind() {
case reflect.String,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Float32,
reflect.Float64,
reflect.Bool:
return nil
default:
slog.Warn(fmt.Sprintf("type %s for %s param is not reccomended", t.Kind().String(), specifiedKind))
return nil
}
case "file":
if t != reflect.TypeOf(new(File)) {
return fmt.Errorf("type for a param of kind file MUST be a pointer to File")
}
case "form":
switch t.Kind() {
case reflect.Struct, reflect.Pointer:
default:
slog.Info("kind for form param is NOT reccomended", "kind", t.Kind().String())
return nil
}
}
return nil
}
// handleParam takes the value as recieved, returns an error if the value
// is empty AND required.
func handleParam(value string, param Parameter) (string, error) {
ok := !(value == "")
if !ok && param.Required {
return "", fmt.Errorf("required %s param %s not provided", param.In, param.Name)
}
return value, nil
}
// validate validates the input string against the type to ensure with options
// from Parameter.
func validate(input map[string]any, schemaType reflect.Type) (bool, error) {
expectedNotFoundKeys := map[string]bool{}
fields := map[string]reflect.StructField{}
for i := range schemaType.NumField() {
field := schemaType.Field(i)
name := field.Name
nameTag := field.Tag.Get("name")
jsonTag := field.Tag.Get("json")
s := strings.Split(jsonTag, ",")
jsonTagName := s[0]
if jsonTagName != "" {
name = jsonTagName
}
if nameTag != "" { // name takes priority over json
name = nameTag
}
fields[name] = field
b, _ := resolveBool(field.Tag.Get("required"), true)
expectedNotFoundKeys[name] = b
}
for k, v := range input {
required, ok := expectedNotFoundKeys[k]
if !ok {
return false, UnexpectedJSONKey(k)
} else {
delete(expectedNotFoundKeys, k)
}
f := fields[k] //cannot error
ft := f.Type
p := ft.Kind() == reflect.Pointer
tr := reflect.TypeOf(v)
if tr == nil {
if required && !p {
return false, BadFieldType(k, "nil", ft.Kind().String())
} else {
continue
}
}
t := tr.Kind()
if ft.Kind() == reflect.Pointer {
ft = ft.Elem()
// p = true
}
switch t {
case reflect.String, reflect.Bool:
if ft.Kind() != t {
return false, BadFieldType(k, t.String(), ft.Kind().String())
}
case reflect.Int:
if isAnyOfThese(ft.Kind(), reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64) {
if !(v.(int) >= 0) {
return false, BadFieldType(k, t.String(), ft.Kind().String())
}
} else if !isAnyOfThese(ft.Kind(), reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64) {
return false, BadFieldType(k, t.String(), ft.Kind().String())
}
case reflect.Float32, reflect.Float64:
if !isAnyOfThese(ft.Kind(), reflect.Float32, reflect.Float64) {
return false, BadFieldType(k, t.String(), ft.Kind().String())
}
case reflect.Array, reflect.Slice:
if reflect.TypeOf(v).AssignableTo(f.Type) {
return false, BadFieldType(k, ft.String(), reflect.TypeOf(v).String())
}
case reflect.Map:
if ft.Kind() != reflect.Struct {
return false, BadFieldType(k, t.String(), ft.Kind().String())
}
return validate(v.(map[string]any), ft)
default:
return false, BadFieldType(k, "unsupported type: "+t.String(), ft.Kind().String())
}
}
for k, required := range expectedNotFoundKeys {
if required {
return false, ExpectedButNotFound(k)
}
}
return true, nil
}
// getRequestHeaderParam gets the value of the param from the header. It may return error
// if it not found AND required.
func getRequestHeaderParam(c *Context, param Parameter) (string, error) {
value := c.GetRequestHeader(param.Name)
return handleParam(value, param)
}
// getQueryParam gets the value of the param from the query. It may return error
// if it not found AND required.
func getQueryParam(c *Context, param Parameter) (string, error) {
//FIXME: only the first letter should be lowered.
value := c.GetQueryParam(param.Name)
return handleParam(value, param)
}
// getCookieParam gets the value of the param from the cookie header.
// It may return an error if it not found AND required.
func getCookieParam(c *Context, param Parameter) (string, error) {
value := c.GetCookie(param.Name)
return handleParam(value, param)
}
func getPathParam(index int, param Parameter, matches []string) (string, error) {
if len(matches) > 1+index {
m := matches[1+index]
return handleParam(m, param)
} else {
return "", fmt.Errorf("required path param %s not provided", param.Name)
}
}
// getBodyParam gets the value of the param from the body.
// It will return an error if it is not found AND required.
func getBodyParam(c *Context, param Parameter) (string, error) {
// Read the body content
body, err := c.GetBody()
if err != nil {
return "", fmt.Errorf("an error occurred while reading the body: %s", err.Error())
}
return handleParam(string(body), param)
}
func getFormParam(c *Context, param Parameter) (string, error) {
return handleParam(c.GetFormValue(param.Name), param)
}
func populateField(value string, field reflect.Value) error {
fieldType := field.Type()
switch fieldType.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
valuei, err := strconv.Atoi(value)
if err != nil {
return FieldTypeError(value, fieldType.Kind().String())
}
switch fieldType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
field.SetInt(int64(valuei))
default:
if valuei < 0 {
return FieldTypeError(value, fieldType.Kind().String())
}
valueui := uint64(valuei)
field.SetUint(valueui)
}
case reflect.Float32, reflect.Float64:
valuef, err := strconv.ParseFloat(value, 64)
if err != nil {
return FieldTypeError(value, "float32")
}
field.SetFloat(valuef)
case reflect.Bool:
valueb, err := strconv.ParseBool(value)
if err != nil {
return FieldTypeError(value, "boolean")
}
field.SetBool(valueb)
case reflect.Struct:
var m map[string]any
err := json.Unmarshal([]byte(value), &m)
if err != nil {
return InvalidJSONError(value)
}
ok, err := validate(m, fieldType)
if !ok {
return err
}
newField := reflect.New(fieldType)
err = json.Unmarshal([]byte(value), newField.Interface())
if err != nil {
return FieldTypeError(value, fieldType.Name())
}
field.Set(newField.Elem())
}
return nil
}
func populateInputSchema(c *Context, s any, p []Parameter, matches []string) error {
if len(p) == 0 { //no input schema
return nil
}
// FIXME: allow user to specify memory
c.Request.ParseMultipartForm(10 << 20) // leftshift to represent 10 mb
sve := reflect.ValueOf(s).Elem() //will not panic because we can confirm
pathparamsindex := 0 //pathparamsindex is the amount of path params already reviewed
for i, pa := range p {
var value string
var err error
switch pa.In {
case "header":
value, err = getRequestHeaderParam(c, pa)
case "path":
value, err = getPathParam(pathparamsindex, pa, matches)
case "query":
value, err = getQueryParam(c, pa)
case "cookie":
value, err = getCookieParam(c, pa)
case "body":
value, err = getBodyParam(c, pa)
case "form":
value, err = getFormParam(c, pa)
case "file":
// special case since we're populating to *puff.File
newFile := new(File)
file, fileHeader, err := c.GetFormFile(pa.Name)
if err != nil {
return err
}
if fileHeader == nil {
return fmt.Errorf("file header is nil")
}
newFile.Name = fileHeader.Filename
newFile.Size = fileHeader.Size
newFile.MultipartFile = file
f := sve.Field(i)
f.Set(reflect.ValueOf(newFile))
continue
}
if err != nil {
return err
}
field := sve.Field(i) //has to be there because handleInputSchema
err = populateField(value, field)
if err != nil {
return err
}
}
return nil
}
type typeInfo struct {
_type string
info Schema
}
func newTypeInfo(_type string, s Schema) typeInfo {
return typeInfo{
_type: _type,
info: s,
}
}
var supportedTypes = map[string]typeInfo{
"string": newTypeInfo("string", Schema{
Format: "string",
Examples: []any{"string"},
}),
"int": newTypeInfo("integer", Schema{
Format: "int",
Examples: []any{"255"},
}),
"int8": newTypeInfo("number", Schema{
// https://spec.openapis.org/registry/format/int8
Format: "int8",
Examples: []any{"0"},
}),
"int16": newTypeInfo("number", Schema{
// https://spec.openapis.org/registry/format/int16
Format: "int16",
Examples: []any{"0"},
}),
"int32": newTypeInfo("number", Schema{
// https://spec.openapis.org/registry/format/int32
Format: "int32",
Examples: []any{"0"},
}),
"int64": newTypeInfo("number", Schema{
// https://spec.openapis.org/registry/format/int64
Format: "int64",
Examples: []any{"0"},
}),
"uint": newTypeInfo("integer", Schema{
Format: "int",
Minimum: "0",
Examples: []any{"0"},
}),
"uint8": newTypeInfo("integer", Schema{
Format: "int8",
Examples: []any{"0"},
Minimum: "0",
}),
"uint16": newTypeInfo("integer", Schema{
Format: "int16",
Examples: []any{"0"},
Minimum: "0",
}),
"uint32": newTypeInfo("integer", Schema{
Format: "int32",
Examples: []any{"0"},
Minimum: "0",
}),
"uint64": newTypeInfo("integer", Schema{
Format: "int64",
Examples: []any{"0"},
Minimum: strconv.Itoa(2 ^ 64 - 1),
}),
"float32": newTypeInfo("number", Schema{
Format: "float",
Examples: []any{"0.01"},
}),
"float64": newTypeInfo("number", Schema{
Format: "double",
Examples: []any{"0.0"},
Minimum: "0.01",
}),
"bool": newTypeInfo("boolean", Schema{
Format: "bool",
Examples: []any{false},
}),
}
func newDefinition(route *Route, schema any) *Schema {
st := reflect.TypeOf(schema)
sv := reflect.ValueOf(schema)
// Handle pointer types
if st.Kind() == reflect.Pointer {
st = st.Elem()
sv = sv.Elem()
}
switch st.Kind() {
case reflect.Map:
return handleMapType(route, st)
case reflect.Array, reflect.Slice:
return handleArrayType(route, st)
case reflect.Struct:
return handleStructType(route, st, sv)
default:
return handleBasicType(st)
}
}
// handleBasicType will handle generating Schema for types such as int, string, and others
func handleBasicType(st reflect.Type) *Schema {
ts, ok := supportedTypes[st.String()]
if !ok {
panic(fmt.Sprintf("Unsupported type: %s.", st.String()))
}
return &ts.info
}
// Handle map types
func handleMapType(route *Route, st reflect.Type) *Schema {
if st.Key().Kind() != reflect.String {
panic("Map key type must always be string.")
}
valueSchema := newDefinition(route, reflect.Zero(st.Elem()).Interface())
return &Schema{
AdditionalProperties: valueSchema,
}
}
// Handle array or slice types
func handleArrayType(route *Route, st reflect.Type) *Schema {
itemSchema := newDefinition(route, reflect.Zero(st.Elem()).Interface())
return &Schema{
Type: "array",
Items: itemSchema,
}
}
// Handle struct types
func handleStructType(route *Route, st reflect.Type, sv reflect.Value) *Schema {
// Handle special `File` type
if st == reflect.TypeOf((*File)(nil)).Elem() || st == reflect.TypeOf(File{}) {
return &Schema{
Ref: "$FILE",
}
}
// Process struct fields
newDef := Schema{
Type: "object",
Properties: make(map[string]*Schema),
Required: []string{},
}
for i := 0; i < st.NumField(); i++ {
field := st.Field(i)
fieldSchema := newDefinition(route, sv.Field(i).Interface())
fieldName := parseJSONTag(field.Tag)
if fieldName == "" {
fieldName = field.Name
}
if isFieldRequired(field.Tag) {
newDef.Required = append(newDef.Required, fieldName)
}
newDef.Properties[fieldName] = fieldSchema
}
Schemas[st.Name()] = &newDef
return &Schema{
Ref: "#/components/schemas/" + st.Name(),
}
}
// parseJSONTag is a helper method to grab the json field
func parseJSONTag(tag reflect.StructTag) string {
jsonTag := tag.Get("json")
if jsonTag == "" {
return ""
}
return strings.Split(jsonTag, ",")[0]
}
// isFieldRequired is a helpermethod to grab the 'required' value
func isFieldRequired(tag reflect.StructTag) bool {
requiredTag := tag.Get("required")
isRequired, err := resolveBool(requiredTag, true)
if err != nil {
panic(err)
}
return isRequired
}