multipart_form_mapping.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 Gin Core Team. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "errors"
  7. "mime/multipart"
  8. "net/http"
  9. "reflect"
  10. )
  11. type multipartRequest http.Request
  12. var _ setter = (*multipartRequest)(nil)
  13. // TrySet tries to set a value by the multipart request with the binding a form file
  14. func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error) {
  15. if files := r.MultipartForm.File[key]; len(files) != 0 {
  16. return setByMultipartFormFile(value, field, files)
  17. }
  18. return setByForm(value, field, r.MultipartForm.Value, key, opt)
  19. }
  20. func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSetted bool, err error) {
  21. switch value.Kind() {
  22. case reflect.Ptr:
  23. switch value.Interface().(type) {
  24. case *multipart.FileHeader:
  25. value.Set(reflect.ValueOf(files[0]))
  26. return true, nil
  27. }
  28. case reflect.Struct:
  29. switch value.Interface().(type) {
  30. case multipart.FileHeader:
  31. value.Set(reflect.ValueOf(*files[0]))
  32. return true, nil
  33. }
  34. case reflect.Slice:
  35. slice := reflect.MakeSlice(value.Type(), len(files), len(files))
  36. isSetted, err = setArrayOfMultipartFormFiles(slice, field, files)
  37. if err != nil || !isSetted {
  38. return isSetted, err
  39. }
  40. value.Set(slice)
  41. return true, nil
  42. case reflect.Array:
  43. return setArrayOfMultipartFormFiles(value, field, files)
  44. }
  45. return false, errors.New("unsupported field type for multipart.FileHeader")
  46. }
  47. func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSetted bool, err error) {
  48. if value.Len() != len(files) {
  49. return false, errors.New("unsupported len of array for []*multipart.FileHeader")
  50. }
  51. for i := range files {
  52. setted, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1])
  53. if err != nil || !setted {
  54. return setted, err
  55. }
  56. }
  57. return true, nil
  58. }