...

Source file src/github.com/gin-gonic/gin/binding/multipart_form_mapping.go

Documentation: github.com/gin-gonic/gin/binding

     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  
     5  package binding
     6  
     7  import (
     8  	"errors"
     9  	"mime/multipart"
    10  	"net/http"
    11  	"reflect"
    12  )
    13  
    14  type multipartRequest http.Request
    15  
    16  var _ setter = (*multipartRequest)(nil)
    17  
    18  var (
    19  	// ErrMultiFileHeader multipart.FileHeader invalid
    20  	ErrMultiFileHeader = errors.New("unsupported field type for multipart.FileHeader")
    21  
    22  	// ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid
    23  	ErrMultiFileHeaderLenInvalid = errors.New("unsupported len of array for []*multipart.FileHeader")
    24  )
    25  
    26  // TrySet tries to set a value by the multipart request with the binding a form file
    27  func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (bool, error) {
    28  	if files := r.MultipartForm.File[key]; len(files) != 0 {
    29  		return setByMultipartFormFile(value, field, files)
    30  	}
    31  
    32  	return setByForm(value, field, r.MultipartForm.Value, key, opt)
    33  }
    34  
    35  func setByMultipartFormFile(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) {
    36  	switch value.Kind() {
    37  	case reflect.Ptr:
    38  		switch value.Interface().(type) {
    39  		case *multipart.FileHeader:
    40  			value.Set(reflect.ValueOf(files[0]))
    41  			return true, nil
    42  		}
    43  	case reflect.Struct:
    44  		switch value.Interface().(type) {
    45  		case multipart.FileHeader:
    46  			value.Set(reflect.ValueOf(*files[0]))
    47  			return true, nil
    48  		}
    49  	case reflect.Slice:
    50  		slice := reflect.MakeSlice(value.Type(), len(files), len(files))
    51  		isSet, err = setArrayOfMultipartFormFiles(slice, field, files)
    52  		if err != nil || !isSet {
    53  			return isSet, err
    54  		}
    55  		value.Set(slice)
    56  		return true, nil
    57  	case reflect.Array:
    58  		return setArrayOfMultipartFormFiles(value, field, files)
    59  	}
    60  	return false, ErrMultiFileHeader
    61  }
    62  
    63  func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField, files []*multipart.FileHeader) (isSet bool, err error) {
    64  	if value.Len() != len(files) {
    65  		return false, ErrMultiFileHeaderLenInvalid
    66  	}
    67  	for i := range files {
    68  		set, err := setByMultipartFormFile(value.Index(i), field, files[i:i+1])
    69  		if err != nil || !set {
    70  			return set, err
    71  		}
    72  	}
    73  	return true, nil
    74  }
    75  

View as plain text