From 0fb7bed1c0c701958d0319018ccdda7e851163e0 Mon Sep 17 00:00:00 2001 From: Aleksandr Didenko Date: Sun, 8 Mar 2015 15:43:37 +0100 Subject: [PATCH] Added support multipart/form-data #109 --- binding/binding.go | 24 ++++++++++++++++++++---- context.go | 2 ++ gin.go | 15 ++++++++------- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/binding/binding.go b/binding/binding.go index b49f1e5..f72b943 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -25,14 +25,20 @@ type ( // XML binding xmlBinding struct{} - // // form binding + // form binding formBinding struct{} + + // multipart form binding + multipartFormBinding struct{} ) +const MAX_MEMORY = 1 * 1024 * 1024 + var ( - JSON = jsonBinding{} - XML = xmlBinding{} - Form = formBinding{} // todo + JSON = jsonBinding{} + XML = xmlBinding{} + Form = formBinding{} // todo + MultipartForm = multipartFormBinding{} ) func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error { @@ -63,6 +69,16 @@ func (_ formBinding) Bind(req *http.Request, obj interface{}) error { return Validate(obj) } +func (_ multipartFormBinding) Bind(req *http.Request, obj interface{}) error { + if err := req.ParseMultipartForm(MAX_MEMORY); err != nil { + return err + } + if err := mapForm(obj, req.Form); err != nil { + return err + } + return Validate(obj) +} + func mapForm(ptr interface{}, form map[string][]string) error { typ := reflect.TypeOf(ptr).Elem() formStruct := reflect.ValueOf(ptr).Elem() diff --git a/context.go b/context.go index c39d5e2..d877514 100644 --- a/context.go +++ b/context.go @@ -295,6 +295,8 @@ func (c *Context) Bind(obj interface{}) bool { switch { case c.Request.Method == "GET" || ctype == MIMEPOSTForm: b = binding.Form + case ctype == MIMEMultipartPOSTForm: + b = binding.MultipartForm case ctype == MIMEJSON: b = binding.JSON case ctype == MIMEXML || ctype == MIMEXML2: diff --git a/gin.go b/gin.go index 42c4b1f..3e7181c 100644 --- a/gin.go +++ b/gin.go @@ -14,13 +14,14 @@ import ( ) const ( - AbortIndex = math.MaxInt8 / 2 - MIMEJSON = "application/json" - MIMEHTML = "text/html" - MIMEXML = "application/xml" - MIMEXML2 = "text/xml" - MIMEPlain = "text/plain" - MIMEPOSTForm = "application/x-www-form-urlencoded" + AbortIndex = math.MaxInt8 / 2 + MIMEJSON = "application/json" + MIMEHTML = "text/html" + MIMEXML = "application/xml" + MIMEXML2 = "text/xml" + MIMEPlain = "text/plain" + MIMEPOSTForm = "application/x-www-form-urlencoded" + MIMEMultipartPOSTForm = "multipart/form-data" ) type (