Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get Body From Context #1253

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions binding/body.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package binding

import "net/url"

// Body type map[string]interface{}
type Body map[string]interface{}

// ToBody transforms object into Body type.
func ToBody(in interface{}) *Body {
switch in.(type) {
case Body:
res := in.(Body)

return &res
case url.Values:
result := make(Body)

for key, value := range in.(url.Values) {
if len(value) == 1 {
result[key] = value[0]
} else {
result[key] = value
}
}

return &result
}

return new(Body)
}
29 changes: 29 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package gin

import (
"encoding/json"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -59,6 +60,8 @@ type Context struct {

// Accepted defines a list of manually accepted formats for content negotiation.
Accepted []string

body *binding.Body
}

/************************************/
Expand Down Expand Up @@ -1021,3 +1024,29 @@ func (c *Context) Value(key interface{}) interface{} {
}
return nil
}

// Body parses body content
//
func (c *Context) Body() (*binding.Body, error) {
if c.body != nil {
return c.body, nil
}

var err error
body := new(binding.Body)

switch c.ContentType() {
case MIMEJSON:
err = json.NewDecoder(c.Request.Body).Decode(&body)
case MIMEPOSTForm:
err = c.Request.ParseForm()
body = binding.ToBody(c.Request.Form)
case MIMEMultipartPOSTForm:
_, err = c.MultipartForm()
body = binding.ToBody(c.Request.Form)
}

c.body = body

return body, err
}