Debian Codegraph @

binding.go

raw symbols SCIP
1 // Copyright 2014 Martini Authors
2 // Copyright 2014 The Macaron Authors
3 // Copyright 2020 The Gitea Authors
4 // Copyright 2024 The Forgejo Authors
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License"): you may
7 // not use this file except in compliance with the License. You may obtain
8 // a copy of the License at
9 //
10 // http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 // License for the specific language governing permissions and limitations
16 // under the License.
17
18 // Package binding is a middleware that provides request data binding and validation for Chi.
19 package binding
20
21 import (
22 "encoding/json"
23 "fmt"
24 "io"
25 "mime/multipart"
26 "net/http"
27 "net/url"
28 "reflect"
29 "regexp"
30 "slices"
31 "strconv"
32 "strings"
33 "unicode/utf8"
34 )
35
36 // Bind wraps up the functionality of the Form and Json middleware
37 // according to the Content-Type and verb of the request.
38 // A Content-Type is required for POST and PUT requests.
39 // Bind invokes the ErrorHandler middleware to bail out if errors
40 // occurred. If you want to perform your own error handling, use
41 // Form or Json middleware directly. An interface pointer can
42 // be added as a second argument in order to map the struct to
43 // a specific interface.
44 func Bind(req *http.Request, obj any) Errors {
45 contentType := req.Header.Get("Content-Type")
46 if req.Method == "POST" || req.Method == "PUT" || len(contentType) > 0 {
47 switch {
48 case strings.Contains(contentType, "form-urlencoded"):
49 return Form(req, obj)
50 case strings.Contains(contentType, "multipart/form-data"):
51 return MultipartForm(req, obj)
52 case strings.Contains(contentType, "json"):
53 return JSON(req, obj)
54 default:
55 var errors Errors
56 if contentType == "" {
57 errors.Add([]string{}, ERR_CONTENT_TYPE, "Empty Content-Type")
58 } else {
59 errors.Add([]string{}, ERR_CONTENT_TYPE, "Unsupported Content-Type")
60 }
61 return errors
62 }
63 } else {
64 return Form(req, obj)
65 }
66 }
67
68 const jsonContentType = "application/json; charset=utf-8"
69
70 // errorHandler simply counts the number of errors in the
71 // context and, if more than 0, writes a response with an
72 // error code and a JSON payload describing the errors.
73 // The response will have a JSON content-type.
74 // Middleware remaining on the stack will not even see the request
75 // if, by this point, there are any errors.
76 // This is a "default" handler, of sorts, and you are
77 // welcome to use your own instead. The Bind middleware
78 // invokes this automatically for convenience.
79 func errorHandler(errs Errors, rw http.ResponseWriter) {
80 if len(errs) > 0 {
81 rw.Header().Set("Content-Type", jsonContentType)
82 switch {
83 case errs.Has(ERR_DESERIALIZATION):
84 rw.WriteHeader(http.StatusBadRequest)
85 case errs.Has(ERR_CONTENT_TYPE):
86 rw.WriteHeader(http.StatusUnsupportedMediaType)
87 default:
88 rw.WriteHeader(http.StatusUnprocessableEntity)
89 }
90 errOutput, _ := json.Marshal(errs)
91 _, _ = rw.Write(errOutput)
92 return
93 }
94 }
95
96 // Form is middleware to deserialize form-urlencoded data from the request.
97 // It gets data from the form-urlencoded body, if present, or from the
98 // query string. It uses the http.Request.ParseForm() method
99 // to perform deserialization, then reflection is used to map each field
100 // into the struct with the proper type. Structs with primitive slice types
101 // (bool, float, int, string) can support deserialization of repeated form
102 // keys, for example: key=val1&key=val2&key=val3
103 // An interface pointer can be added as a second argument in order
104 // to map the struct to a specific interface.
105 func Form(req *http.Request, formStruct any) Errors {
106 var errors Errors
107
108 ensurePointer(formStruct)
109 formStructV := reflect.ValueOf(formStruct)
110 parseErr := req.ParseForm()
111
112 // Format validation of the request body or the URL would add considerable overhead,
113 // and ParseForm does not complain when URL encoding is off.
114 // Because an empty request body or url can also mean absence of all needed values,
115 // it is not in all cases a bad request, so let's return 422.
116 if parseErr != nil {
117 errors.Add([]string{}, ERR_DESERIALIZATION, parseErr.Error())
118 }
119 errors = mapForm(formStructV, req.Form, nil, errors)
120 return append(errors, Validate(req, formStruct)...)
121 }
122
123 // MaxMemory represents maximum amount of memory to use when parsing a multipart form.
124 // Set this to whatever value you prefer; default is 10 MB.
125 var MaxMemory = int64(1024 * 1024 * 10)
126
127 // MultipartForm works much like Form, except it can parse multipart forms
128 // and handle file uploads. Like the other deserialization middleware handlers,
129 // you can pass in an interface to make the interface available for injection
130 // into other handlers later.
131 func MultipartForm(req *http.Request, formStruct any) Errors {
132 var errors Errors
133 ensurePointer(formStruct)
134 formStructV := reflect.ValueOf(formStruct)
135 // This if check is necessary due to https://github.com/martini-contrib/csrf/issues/6
136 if req.MultipartForm == nil {
137 // Workaround for multipart forms returning nil instead of an error
138 // when content is not multipart; see https://code.google.com/p/go/issues/detail?id=6334
139 if multipartReader, err := req.MultipartReader(); err != nil {
140 errors.Add([]string{}, ERR_DESERIALIZATION, err.Error())
141 } else {
142 form, parseErr := multipartReader.ReadForm(MaxMemory)
143 if parseErr != nil {
144 errors.Add([]string{}, ERR_DESERIALIZATION, parseErr.Error())
145 }
146
147 if req.Form == nil {
148 _ = req.ParseForm()
149 }
150 if form == nil {
151 return append(errors, Validate(req, formStruct)...)
152 }
153 for k, v := range form.Value {
154 req.Form[k] = append(req.Form[k], v...)
155 }
156
157 req.MultipartForm = form
158 }
159 }
160 errors = mapForm(formStructV, req.MultipartForm.Value, req.MultipartForm.File, errors)
161 return append(errors, Validate(req, formStruct)...)
162 }
163
164 // JSON is middleware to deserialize a JSON payload from the request
165 // into the struct that is passed in. The resulting struct is then
166 // validated, but no error handling is actually performed here.
167 // An interface pointer can be added as a second argument in order
168 // to map the struct to a specific interface.
169 func JSON(req *http.Request, jsonStruct any) Errors {
170 var errors Errors
171 ensurePointer(jsonStruct)
172
173 if req.Body != nil {
174 defer req.Body.Close()
175 err := json.NewDecoder(req.Body).Decode(jsonStruct)
176 if err != nil && err != io.EOF {
177 errors.Add([]string{}, ERR_DESERIALIZATION, err.Error())
178 }
179 }
180 return append(errors, Validate(req, jsonStruct)...)
181 }
182
183 // RawValidate is same as Validate but does not require a HTTP context,
184 // and can be used independently just for validation.
185 // This function does not support Validator interface.
186 func RawValidate(obj any) Errors {
187 var errs Errors
188 v := reflect.ValueOf(obj)
189 k := v.Kind()
190 if k == reflect.Interface || k == reflect.Ptr {
191 v = v.Elem()
192 k = v.Kind()
193 }
194 if k == reflect.Slice || k == reflect.Array {
195 for i := 0; i < v.Len(); i++ {
196 e := v.Index(i).Interface()
197 errs = validateStruct(errs, e)
198 }
199 } else {
200 errs = validateStruct(errs, obj)
201 }
202 return errs
203 }
204
205 // Validate is middleware to enforce required fields. If the struct
206 // passed in implements Validator, then the user-defined Validate method
207 // is executed, and its errors are mapped to the context. This middleware
208 // performs no error handling: it merely detects errors and maps them.
209 func Validate(req *http.Request, obj any) Errors {
210 var errs Errors
211 v := reflect.ValueOf(obj)
212 k := v.Kind()
213 if k == reflect.Interface || k == reflect.Ptr {
214 v = v.Elem()
215 k = v.Kind()
216 }
217 if k == reflect.Slice || k == reflect.Array {
218 for i := 0; i < v.Len(); i++ {
219 e := v.Index(i).Interface()
220 errs = validateStruct(errs, e)
221 if validator, ok := e.(Validator); ok {
222 errs = validator.Validate(req, errs)
223 }
224 }
225 } else {
226 errs = validateStruct(errs, obj)
227 if validator, ok := obj.(Validator); ok {
228 errs = validator.Validate(req, errs)
229 }
230 }
231 return errs
232 }
233
234 var (
235 AlphaDashPattern = regexp.MustCompile(`[^\d\w-_]`)
236 AlphaDashDotPattern = regexp.MustCompile(`[^\d\w-_\.]`)
237 EmailPattern = regexp.MustCompile(`\A[\w!#$%&'*+/=?^_` + "`" + `{|}~-]+(?:\.[\w!#$%&'*+/=?^_` + "`" + `{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[a-zA-Z0-9](?:[\w-]*[\w])?\z`)
238 )
239
240 // Copied from github.com/asaskevich/govalidator.
241 const (
242 maxURLRuneCount = 2083
243 minURLRuneCount = 3
244 )
245
246 var (
247 urlSchemaRx = `((ftp|tcp|udp|wss?|https?):\/\/)`
248 urlUsernameRx = `(\S+(:\S*)?@)`
249 urlIPRx = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
250 ipRx = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))`
251 urlSubdomainRx = `((www\.)|([a-zA-Z0-9]([-\.][-\._a-zA-Z0-9]+)*))`
252 urlPortRx = `(:(\d{1,5}))`
253 urlPathRx = `((\/|\?|#)[^\s]*)`
254 URLPattern = regexp.MustCompile(`\A` + urlSchemaRx + `?` + urlUsernameRx + `?` + `((` + urlIPRx + `|(\[` + ipRx + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + urlSubdomainRx + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + urlPortRx + `?` + urlPathRx + `?\z`)
255 )
256
257 // IsURL check if the string is an URL.
258 func isURL(str string) bool {
259 if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") {
260 return false
261 }
262 u, err := url.Parse(str)
263 if err != nil {
264 return false
265 }
266 if strings.HasPrefix(u.Host, ".") {
267 return false
268 }
269 if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
270 return false
271 }
272 return URLPattern.MatchString(str)
273 }
274
275 type (
276 // Rule represents a validation rule.
277 Rule struct {
278 // IsMatch checks if rule matches.
279 IsMatch func(string) bool
280 // IsValid applies validation rule to condition.
281 IsValid func(Errors, string, any) (bool, Errors)
282 }
283
284 // ParamRule does same thing as Rule but passes rule itself to IsValid method.
285 ParamRule struct {
286 // IsMatch checks if rule matches.
287 IsMatch func(string) bool
288 // IsValid applies validation rule to condition.
289 IsValid func(Errors, string, string, any) (bool, Errors)
290 }
291
292 // RuleMapper and ParamRuleMapper represent validation rule mappers,
293 // it allwos users to add custom validation rules.
294 RuleMapper []*Rule
295 ParamRuleMapper []*ParamRule
296 )
297
298 var (
299 ruleMapper RuleMapper
300 paramRuleMapper ParamRuleMapper
301 )
302
303 // AddRule adds new validation rule.
304 func AddRule(r *Rule) {
305 ruleMapper = append(ruleMapper, r)
306 }
307
308 // AddParamRule adds new validation rule.
309 func AddParamRule(r *ParamRule) {
310 paramRuleMapper = append(paramRuleMapper, r)
311 }
312
313 func in(fieldValue any, arr string) bool {
314 val := fmt.Sprintf("%v", fieldValue)
315 vals := strings.Split(arr, ",")
316 isIn := false
317 for _, v := range vals {
318 if v == val {
319 isIn = true
320 break
321 }
322 }
323 return isIn
324 }
325
326 func parseFormName(raw, actual string) string {
327 if len(actual) > 0 {
328 return actual
329 }
330 return nameMapper(raw)
331 }
332
333 // Performs required field checking on a struct
334 func validateStruct(errors Errors, obj any) Errors {
335 typ := reflect.TypeOf(obj)
336 val := reflect.ValueOf(obj)
337
338 if typ.Kind() == reflect.Ptr {
339 typ = typ.Elem()
340 val = val.Elem()
341 }
342
343 for i := 0; i < typ.NumField(); i++ {
344 field := typ.Field(i)
345
346 // Allow ignored fields in the struct
347 if field.Tag.Get("form") == "-" || !val.Field(i).CanInterface() {
348 continue
349 }
350
351 fieldVal := val.Field(i)
352 fieldValue := fieldVal.Interface()
353 zero := reflect.Zero(field.Type).Interface()
354
355 // Validate nested and embedded structs (if pointer, only do so if not nil)
356 if field.Type.Kind() == reflect.Struct ||
357 (field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue) &&
358 field.Type.Elem().Kind() == reflect.Struct) {
359 errors = validateStruct(errors, fieldValue)
360 continue
361 }
362
363 if fieldVal.Kind() == reflect.Ptr {
364 isZero := reflect.DeepEqual(zero, fieldValue)
365
366 zero = reflect.Zero(fieldVal.Type().Elem()).Interface()
367 fieldVal = fieldVal.Elem()
368
369 if isZero {
370 fieldValue = zero
371 } else {
372 fieldValue = fieldVal.Interface()
373 }
374 }
375
376 errors = validateField(errors, zero, field, fieldVal, fieldValue)
377 }
378 return errors
379 }
380
381 // Don't pass in pointers to bind to. Can lead to bugs.
382 func ensureNotPointer(obj any) {
383 if reflect.TypeOf(obj).Kind() == reflect.Ptr {
384 panic("Pointers are not accepted as binding models")
385 }
386 }
387
388 func validateField(errors Errors, zero any, field reflect.StructField, fieldVal reflect.Value, fieldValue any) Errors {
389 if fieldVal.Kind() == reflect.Slice {
390 for i := 0; i < fieldVal.Len(); i++ {
391 sliceVal := fieldVal.Index(i)
392 if sliceVal.Kind() == reflect.Ptr {
393 sliceVal = sliceVal.Elem()
394 }
395
396 sliceValue := sliceVal.Interface()
397 zero := reflect.Zero(sliceVal.Type()).Interface()
398 if sliceVal.Kind() == reflect.Struct ||
399 (sliceVal.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, sliceValue) &&
400 sliceVal.Elem().Kind() == reflect.Struct) {
401 errors = validateStruct(errors, sliceValue)
402 }
403 /* Apply validation rules to each item in a slice. ISSUE #3
404 else {
405 errors = validateField(errors, zero, field, sliceVal, sliceValue)
406 }*/
407 }
408 }
409
410 rules := strings.Split(field.Tag.Get("binding"), ";")
411 preProcessorRules := strings.Split(field.Tag.Get("preprocess"), ";")
412
413 if reflect.DeepEqual(zero, fieldValue) {
414 for _, rule := range rules {
415 if rule == "Required" {
416 errors.Add([]string{field.Name}, ERR_REQUIRED, "Required")
417 break
418 }
419 if strings.HasPrefix(rule, "Default(") {
420 if fieldVal.CanSet() {
421 errors = setWithProperType(field.Type.Kind(), rule[8:len(rule)-1], fieldVal, field.Tag.Get("form"), preProcessorRules, errors)
422 } else {
423 errors.Add([]string{field.Name}, ERR_EXCLUDE, "Default")
424 }
425 break
426 }
427 }
428
429 return errors
430 }
431
432 VALIDATE_RULES:
433 for _, rule := range rules {
434 if len(rule) == 0 {
435 continue
436 }
437
438 switch {
439 case rule == "Required":
440 continue
441 case strings.HasPrefix(rule, "Default("):
442 continue
443 case rule == "OmitEmpty": // legacy
444 continue
445
446 case rule == "AlphaDash":
447 if AlphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
448 errors.Add([]string{field.Name}, ERR_ALPHA_DASH, "AlphaDash")
449 break VALIDATE_RULES
450 }
451 case rule == "AlphaDashDot":
452 if AlphaDashDotPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
453 errors.Add([]string{field.Name}, ERR_ALPHA_DASH_DOT, "AlphaDashDot")
454 break VALIDATE_RULES
455 }
456 case strings.HasPrefix(rule, "Size("):
457 size, _ := strconv.Atoi(rule[5 : len(rule)-1])
458 if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) != size {
459 errors.Add([]string{field.Name}, ERR_SIZE, "Size")
460 break VALIDATE_RULES
461 }
462 if fieldVal.Kind() == reflect.Slice && fieldVal.Len() != size {
463 errors.Add([]string{field.Name}, ERR_SIZE, "Size")
464 break VALIDATE_RULES
465 }
466 case strings.HasPrefix(rule, "MinSize("):
467 minSize, _ := strconv.Atoi(rule[8 : len(rule)-1])
468 if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < minSize {
469 errors.Add([]string{field.Name}, ERR_MIN_SIZE, "MinSize")
470 break VALIDATE_RULES
471 }
472 if fieldVal.Kind() == reflect.Slice && fieldVal.Len() < minSize {
473 errors.Add([]string{field.Name}, ERR_MIN_SIZE, "MinSize")
474 break VALIDATE_RULES
475 }
476 case strings.HasPrefix(rule, "MaxSize("):
477 maxSize, _ := strconv.Atoi(rule[8 : len(rule)-1])
478 if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > maxSize {
479 errors.Add([]string{field.Name}, ERR_MAX_SIZE, "MaxSize")
480 break VALIDATE_RULES
481 }
482 if fieldVal.Kind() == reflect.Slice && fieldVal.Len() > maxSize {
483 errors.Add([]string{field.Name}, ERR_MAX_SIZE, "MaxSize")
484 break VALIDATE_RULES
485 }
486 case strings.HasPrefix(rule, "Range("):
487 nums := strings.Split(rule[6:len(rule)-1], ",")
488 if len(nums) != 2 {
489 break VALIDATE_RULES
490 }
491 val, _ := strconv.Atoi(fmt.Sprintf("%v", fieldValue))
492 nums0, _ := strconv.Atoi(nums[0])
493 nums1, _ := strconv.Atoi(nums[1])
494 if val < nums0 || val > nums1 {
495 errors.Add([]string{field.Name}, ERR_RANGE, "Range")
496 break VALIDATE_RULES
497 }
498 case rule == "Email":
499 if !EmailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
500 errors.Add([]string{field.Name}, ERR_EMAIL, "Email")
501 break VALIDATE_RULES
502 }
503 case rule == "Url":
504 str := fmt.Sprintf("%v", fieldValue)
505 if !isURL(str) {
506 errors.Add([]string{field.Name}, ERR_URL, "Url")
507 break VALIDATE_RULES
508 }
509 case strings.HasPrefix(rule, "In("):
510 if !in(fieldValue, rule[3:len(rule)-1]) {
511 errors.Add([]string{field.Name}, ERR_IN, "In")
512 break VALIDATE_RULES
513 }
514 case strings.HasPrefix(rule, "NotIn("):
515 if in(fieldValue, rule[6:len(rule)-1]) {
516 errors.Add([]string{field.Name}, ERR_NOT_INT, "NotIn")
517 break VALIDATE_RULES
518 }
519 case strings.HasPrefix(rule, "Include("):
520 if !strings.Contains(fmt.Sprintf("%v", fieldValue), rule[8:len(rule)-1]) {
521 errors.Add([]string{field.Name}, ERR_INCLUDE, "Include")
522 break VALIDATE_RULES
523 }
524 case strings.HasPrefix(rule, "Exclude("):
525 if strings.Contains(fmt.Sprintf("%v", fieldValue), rule[8:len(rule)-1]) {
526 errors.Add([]string{field.Name}, ERR_EXCLUDE, "Exclude")
527 break VALIDATE_RULES
528 }
529 default:
530 // Apply custom validation rules
531 var isValid bool
532 for i := range ruleMapper {
533 if ruleMapper[i].IsMatch(rule) {
534 isValid, errors = ruleMapper[i].IsValid(errors, field.Name, fieldValue)
535 if !isValid {
536 break VALIDATE_RULES
537 }
538 }
539 }
540 for i := range paramRuleMapper {
541 if paramRuleMapper[i].IsMatch(rule) {
542 isValid, errors = paramRuleMapper[i].IsValid(errors, rule, field.Name, fieldValue)
543 if !isValid {
544 break VALIDATE_RULES
545 }
546 }
547 }
548 }
549 }
550 return errors
551 }
552
553 // NameMapper represents a form tag name mapper.
554 type NameMapper func(string) string
555
556 var nameMapper = func(field string) string {
557 newstr := make([]rune, 0, len(field))
558 for i, chr := range field {
559 if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
560 if i > 0 {
561 newstr = append(newstr, '_')
562 }
563 chr -= ('A' - 'a')
564 }
565 newstr = append(newstr, chr)
566 }
567 return string(newstr)
568 }
569
570 // SetNameMapper sets name mapper.
571 func SetNameMapper(nm NameMapper) {
572 nameMapper = nm
573 }
574
575 // Takes values from the form data and puts them into a struct
576 func mapForm(formStruct reflect.Value, form map[string][]string,
577 formfile map[string][]*multipart.FileHeader, errors Errors,
578 ) Errors {
579 if formStruct.Kind() == reflect.Ptr {
580 formStruct = formStruct.Elem()
581 }
582 typ := formStruct.Type()
583
584 for i := 0; i < typ.NumField(); i++ {
585 typeField := typ.Field(i)
586 structField := formStruct.Field(i)
587
588 if typeField.Type.Kind() == reflect.Ptr && typeField.Anonymous {
589 structField.Set(reflect.New(typeField.Type.Elem()))
590 errors = mapForm(structField.Elem(), form, formfile, errors)
591 if reflect.DeepEqual(structField.Elem().Interface(), reflect.Zero(structField.Elem().Type()).Interface()) {
592 structField.Set(reflect.Zero(structField.Type()))
593 }
594 } else if typeField.Type.Kind() == reflect.Struct {
595 errors = mapForm(structField, form, formfile, errors)
596 }
597
598 inputFieldName := parseFormName(typeField.Name, typeField.Tag.Get("form"))
599 if len(inputFieldName) == 0 || !structField.CanSet() {
600 continue
601 }
602
603 preProcessorRules := strings.Split(typeField.Tag.Get("preprocess"), ";")
604
605 inputValue, exists := form[inputFieldName]
606 if exists {
607 numElems := len(inputValue)
608 if structField.Kind() == reflect.Slice && numElems > 0 {
609 sliceOf := structField.Type().Elem().Kind()
610 slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
611 for i := 0; i < numElems; i++ {
612 errors = setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, preProcessorRules, errors)
613 }
614 formStruct.Field(i).Set(slice)
615 } else {
616 errors = setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, preProcessorRules, errors)
617 }
618 continue
619 }
620
621 inputFile, exists := formfile[inputFieldName]
622 if !exists {
623 continue
624 }
625 fhType := reflect.TypeOf((*multipart.FileHeader)(nil))
626 numElems := len(inputFile)
627 if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType {
628 slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
629 for i := 0; i < numElems; i++ {
630 slice.Index(i).Set(reflect.ValueOf(inputFile[i]))
631 }
632 structField.Set(slice)
633 } else if structField.Type() == fhType {
634 structField.Set(reflect.ValueOf(inputFile[0]))
635 }
636 }
637 return errors
638 }
639
640 // This sets the value in a struct of an indeterminate type to the
641 // matching value from the request (via Form middleware) in the
642 // same type, so that not all deserialized values have to be strings.
643 // Supported types are string, int, float, bool, and ptr of these types.
644 func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, preProcessorRules []string, errors Errors) Errors {
645 switch valueKind {
646 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
647 if val == "" {
648 val = "0"
649 }
650 intVal, err := strconv.ParseInt(val, 10, 64)
651 if err != nil {
652 errors.Add([]string{nameInTag}, ERR_INTERGER_TYPE, "Value could not be parsed as integer")
653 } else {
654 structField.SetInt(intVal)
655 }
656 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
657 if val == "" {
658 val = "0"
659 }
660 uintVal, err := strconv.ParseUint(val, 10, 64)
661 if err != nil {
662 errors.Add([]string{nameInTag}, ERR_INTERGER_TYPE, "Value could not be parsed as unsigned integer")
663 } else {
664 structField.SetUint(uintVal)
665 }
666 case reflect.Bool:
667 if val == "on" {
668 structField.SetBool(true)
669 break
670 }
671
672 if val == "" {
673 val = "false"
674 }
675 boolVal, err := strconv.ParseBool(val)
676 if err != nil {
677 errors.Add([]string{nameInTag}, ERR_BOOLEAN_TYPE, "Value could not be parsed as boolean")
678 } else if boolVal {
679 structField.SetBool(true)
680 }
681 case reflect.Float32:
682 if val == "" {
683 val = "0.0"
684 }
685 floatVal, err := strconv.ParseFloat(val, 32)
686 if err != nil {
687 errors.Add([]string{nameInTag}, ERR_FLOAT_TYPE, "Value could not be parsed as 32-bit float")
688 } else {
689 structField.SetFloat(floatVal)
690 }
691 case reflect.Float64:
692 if val == "" {
693 val = "0.0"
694 }
695 floatVal, err := strconv.ParseFloat(val, 64)
696 if err != nil {
697 errors.Add([]string{nameInTag}, ERR_FLOAT_TYPE, "Value could not be parsed as 64-bit float")
698 } else {
699 structField.SetFloat(floatVal)
700 }
701 case reflect.String:
702 if slices.Contains(preProcessorRules, "TrimSpace") {
703 val = strings.TrimSpace(val)
704 }
705 structField.SetString(val)
706 case reflect.Ptr:
707 newVal := reflect.New(structField.Type().Elem())
708 errors = setWithProperType(structField.Type().Elem().Kind(), val, newVal.Elem(), nameInTag, preProcessorRules, errors)
709 structField.Set(newVal)
710 }
711 return errors
712 }
713
714 // Pointers must be bind to.
715 func ensurePointer(obj any) {
716 if reflect.TypeOf(obj).Kind() != reflect.Ptr {
717 panic("Pointers are only accepted as binding models")
718 }
719 }
720
721 type (
722 // ErrorHandler is the interface that has custom error handling process.
723 ErrorHandler interface {
724 // Error handles validation errors with custom process.
725 Error(*http.Request, Errors)
726 }
727
728 // Validator is the interface that handles some rudimentary
729 // request validation logic so your application doesn't have to.
730 Validator interface {
731 // Validate validates that the request is OK. It is recommended
732 // that validation be limited to checking values for syntax and
733 // semantics, enough to know that you can make sense of the request
734 // in your application. For example, you might verify that a credit
735 // card number matches a valid pattern, but you probably wouldn't
736 // perform an actual credit card authorization here.
737 Validate(*http.Request, Errors) Errors
738 }
739 )