Skip to content

Commit

Permalink
update for supporting file binding
Browse files Browse the repository at this point in the history
  • Loading branch information
p581581 committed Mar 1, 2018
1 parent 5d3f30c commit db0fbd4
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions binding/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ func Default(method, contentType string) Binding {
return ProtoBuf
case MIMEMSGPACK, MIMEMSGPACK2:
return MsgPack
case MIMEMultipartPOSTForm:
return FormMultipart
default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
return Form
}
Expand Down
5 changes: 5 additions & 0 deletions binding/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,10 @@ func (formMultipartBinding) Bind(req *http.Request, obj interface{}) error {
if err := mapForm(obj, req.MultipartForm.Value); err != nil {
return err
}

if err := mapFiles(obj, req); err != nil {
return err
}

return validate(obj)
}
36 changes: 36 additions & 0 deletions binding/form_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,47 @@ package binding

import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"time"
)

func mapFiles(ptr interface{}, req *http.Request) error {
typ := reflect.TypeOf(ptr).Elem()
val := reflect.ValueOf(ptr).Elem()
for i := 0; i < typ.NumField(); i++ {
typeField := typ.Field(i)
structField := val.Field(i)

t := fmt.Sprintf("%s", typeField.Type)
if string(t) != "[]uint8" {
continue
}

inputFieldName := typeField.Tag.Get("form")
if inputFieldName == "" {
inputFieldName = typeField.Name
}

file, _, err := req.FormFile(inputFieldName)
if err != nil {
return err
}

data, err := ioutil.ReadAll(file)
if err != nil {
return err
}

structField.SetBytes(data)

}
return nil
}

func mapForm(ptr interface{}, form map[string][]string) error {
typ := reflect.TypeOf(ptr).Elem()
val := reflect.ValueOf(ptr).Elem()
Expand Down

0 comments on commit db0fbd4

Please sign in to comment.