GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix #216: Enable to call binding multiple times in some formats by delphinus · Pull Request #1341 · gin-gonic/gin

Conversation

@delphinus

@delphinus delphinus commented Apr 29, 2018

Copy link
Copy Markdown

close #216

Reported problems

#216 says some formats in requests' body cannot be bound into different structs by calling multiple times.

type modelA struct {
  Foo string `form:"foo" json:"foo" binding:"required"`
  Bar int64  `form:"bar" json:"bar" binding:"required"`
}

type modelB struct {
  Hoge string `form:"hoge" json:"hoge" xml:"hoge" binding:"required"`
  Fuga int64  `form:"fuga" json:"fuga" xml:"fuga" binding:"required"`
}

func main() {
  r := gin.New()
  r.POST("/json", func(c *gin.Context) {
    fa, fb := modelA{}, modelB{}
    if aerr := c.ShouldBindWith(&fa, binding.JSON); aerr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fa})
    } else if berr := c.ShouldBindWith(&fb, binding.JSON); berr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fb})
    } else {
      c.AbortWithStatusJSON(
        http.StatusBadRequest,
        gin.H{
          "errors": gin.H{
            "modelA": aerr.Error(),
            "modelB": berr.Error(),
          },
        },
      )
    }
  })
  r.Run("0:8080")
}
# modelA can be bound successfully
$ curl -X POST -d '{"foo":"AAA","bar":123}' 0:8080/json | jq
{
  "form": {
    "foo": "AAA",
    "bar": 123
  }
}

# but modelB cannot
$ curl -X POST -d '{"hoge":"BBB","fuga":123}' 0:8080/json | jq
{
  "errors": {
    "modelA": "Key: 'modelA.Bar' Error:Field validation for 'Bar' failed on the 'req
ired' tag\nKey: 'modelA.Foo' Error:Field validation for 'Foo' failed on the 'require
' tag",
    "modelB": "EOF"
  }
}

Proposal to solve this

This PR solves this by adding a new interface binding.BindingBody & a new method c.ShouldBindBodyWith.

...
    // use ShouldBindBodyWith
    if aerr := c.ShouldBindBodyWith(&fa, binding.JSON); aerr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fa})
    } else if berr := c.ShouldBindBodyWith(&fb, binding.JSON); berr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fb})
    } else {
...
# successfully modelB bound
$ curl -X POST -d '{"hoge":"BBB","fuga":123}' 0:8080/json | jq
{
  "form": {
    "hoge": "BBB",
    "fuga": 123
  }
}

And you can mix different formats.

...
    if aerr := c.ShouldBindBodyWith(&fa, binding.JSON); aerr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fa})
    } else if berr := c.ShouldBindBodyWith(&fb, binding.XML); berr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fb})
    } else {
...
$ curl -X POST -d '<?xml version="1.0" encoding="UTF-8"?>\n<root>\n<fuga>123</fuga>\n<hoge>BBB</hoge>\n</root>' 0:8080/json | jq
{
  "form": {
    "hoge": "BBB",
    "fuga": 123
  }
}

I added implementations for JSON, XML, msgpack and protobuf. Other formats, query & forms, are already available to be called multiple times, because they uses parsed req.Form (url.Values) instead of req.Body.

Question

  • If you prefer to this feature, I will add unit tests.
  • I'm worrying about cool naming for bind.BindingBody, c.ShouldBindBodyWith. I'm happy if you give better names.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

kishaningithub, dongshanlang, wamich, sarovin, orihehe, AbhishekKumar012, gaga5lala, leejh903, chaseMengdi, xstnet, and 5 more reacted with thumbs up emoji
All reactions
  • 👍 15 reactions
delphinus added 2 commits April 29, 2018 15:15
delphinus
Add interface to read body bytes in binding
3ae520b
delphinus
Add BindingBody implementation for some binding
e825c37
@codecov

codecov Bot commented Apr 29, 2018 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Codecov Report

Merging #1341 into master will decrease coverage by 0.08%.
The diff coverage is 93.54%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1341      +/-   ##
==========================================
- Coverage   98.27%   98.19%   -0.09%     
==========================================
  Files          34       34              
  Lines        1800     1826      +26     
==========================================
+ Hits         1769     1793      +24     
- Misses         25       26       +1     
- Partials        6        7       +1
Impacted Files Coverage Δ
binding/binding.go 100% <ø> (ø) ⬆️
binding/msgpack.go 100% <100%> (ø) ⬆️
binding/json.go 100% <100%> (ø) ⬆️
binding/protobuf.go 100% <100%> (ø) ⬆️
binding/xml.go 100% <100%> (ø) ⬆️
context.go 96.05% <81.81%> (-0.46%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 6e09ef0...bfb9aab. Read the comment docs.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@appleboy
appleboy requested review from a team, appleboy, javierprovecho and nazwa April 30, 2018 05:51
@appleboy

appleboy commented May 1, 2018

Copy link
Copy Markdown
Member

@thinkerou Can you also help to review this PR? Thanks.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@appleboy
Merge branch 'master' into feature/multiple-binding
1e0e4a8
@thinkerou

thinkerou commented May 1, 2018

Copy link
Copy Markdown
Member

@appleboy OK~

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

thinkerou
thinkerou reviewed May 1, 2018
View reviewed changes
Comment thread context.go Outdated
MIMEPlain = binding.MIMEPlain
MIMEPOSTForm = binding.MIMEPOSTForm
MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
BodyBytesKey = "github.com/gin-gonic/gin/bodyBytes"

@thinkerou thinkerou May 1, 2018 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I don't understand it's mean, a little surprising.
Ohh, understand, but the value maybe BindBodyBytesKey better?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@delphinus delphinus May 3, 2018

Copy link
Copy Markdown
Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure. fixed.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@thinkerou thinkerou May 3, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean: BodyBytesKey = "BindBodyBytesKey", actually I see github.com/gin-gonic/gin/bodyBytes at first feel like import, do you think?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@delphinus delphinus May 3, 2018

Copy link
Copy Markdown
Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, yes, but it is a bit dangerous. c.Get(key)'s key is only a string and this is easy to conflict with user-defined keys. I meant the full import-pathish strings as a private key.

I grepped sources and found BindKey = "_gin-gonic/gin/bindkey" (here). Following this, I want to use BodyBytesKey = "_gin-gonic/gin/bodybyteskey", how about this?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@thinkerou thinkerou May 3, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good, agreed!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

delphinus reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
@thinkerou

thinkerou commented May 1, 2018

Copy link
Copy Markdown
Member

Hi, @delphinus , the PR not need to add BindBody to query and form? Thanks!

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

thinkerou
thinkerou reviewed May 1, 2018
View reviewed changes
Comment thread context.go
// ShouldBindWith for better performance if you need to call only once.
func (c *Context) ShouldBindBodyWith(
obj interface{}, bb binding.BindingBody,
) (err error) {

@thinkerou thinkerou May 1, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe not need named return.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@delphinus delphinus May 3, 2018

Copy link
Copy Markdown
Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this, I should add an explicit declaration var err error because this is needed for reusing body in L527.

// if you use unnamed return value...
func (...) ShouldBindBodyWith(...) error {

  ...

  if body == nil {
    // you need explicit declaration here.
    var err error
    body, err = ioutil.ReadAll(...)
    if err != nil {
      return err
    }
    ...
  }
  return ...
}

I want to simplify the code and use this named return variable.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@thinkerou thinkerou May 3, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, got it! Thanks~

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
thinkerou
thinkerou reviewed May 2, 2018
View reviewed changes
Comment thread context.go Outdated
// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
// body into the context, and reuse when it is called again.
//
// NOTE: This method reads the body before binding. So you should use

@thinkerou thinkerou May 2, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use two spaces, thanks.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
thinkerou
thinkerou reviewed May 2, 2018
View reviewed changes
Comment thread binding/binding.go Outdated
Bind(*http.Request, interface{}) error
}

// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,

@thinkerou thinkerou May 2, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use two spaces, thanks.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@delphinus delphinus May 3, 2018

Copy link
Copy Markdown
Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean “one space”, right? mean to replace ...˽Binding.˽˽BindBody˽is... into ...˽Binding.˽BindBody˽is... ?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@thinkerou thinkerou May 3, 2018

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh....so sorry, one space!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

delphinus reacted with thumbs up emoji
All reactions
  • 👍 1 reaction
@thinkerou

thinkerou commented May 2, 2018

Copy link
Copy Markdown
Member

Hi, @delphinus @appleboy Except for comments, need to add unit test and README, it's OK then LGTM to me. Thanks!

appleboy reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@appleboy appleboy added the feature label May 2, 2018
@appleboy appleboy added this to the 1.3 milestone May 2, 2018
delphinus
Fix to use BindBodyBytesKey for key
2c82901
@delphinus

delphinus commented May 3, 2018

Copy link
Copy Markdown
Author

Hi, @delphinus , the PR not need to add BindBody to query and form? Thanks!

No, it is not needed.

Query binding parses req.URL.Query() every times when it is called.

Form, FormPost and FormMultipart parses req.URL.Query() and/or req.Body and store them into req.Form, req.PostForm when it is called at the first time. And it will reuse at the second time and after.

I will add the tests and try to confirm this.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

delphinus added 2 commits May 3, 2018 17:47
delphinus
Revert "Fix to use BindBodyBytesKey for key"
edc5f44
This reverts commit 2c82901.
delphinus
Use private-like key for body bytes
e68e6d2
@appleboy

appleboy commented May 3, 2018 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

Please add some testing and example in readme.

delphinus reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

delphinus added 2 commits May 5, 2018 17:05
delphinus
Add tests for BindingBody & ShouldBindBodyWith
09a2ba4
delphinus
Add note for README
1cecbd3
@delphinus
delphinus force-pushed the feature/multiple-binding branch from fd12128 to 1cecbd3 Compare May 5, 2018 08:42
@delphinus

delphinus commented May 5, 2018

Copy link
Copy Markdown
Author

Added tests & README. Review again @appleboy 👍

And I wrote gist for Query and FormPost. They can be called by the original c.ShouldBind multiple times and do not need this feature.

https://gist.github.com/delphinus/9db93c9ece3dc0bf093986a8e11c3fb7

thinkerou, appleboy, and jakoblorz reacted with thumbs up emoji
All reactions
  • 👍 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

delphinus
Remove redundant space between sentences
4a60eed
appleboy
appleboy approved these changes May 11, 2018
View reviewed changes
@appleboy
Merge branch 'master' into feature/multiple-binding
bfb9aab
@appleboy
appleboy merged commit 995fa8e into gin-gonic:master May 11, 2018
@appleboy appleboy mentioned this pull request May 11, 2018
Calling bind multiple times #216
Closed
@delphinus
delphinus deleted the feature/multiple-binding branch May 11, 2018 02:35
@delphinus delphinus mentioned this pull request May 31, 2018
How to access the Request.Body after ShouldBind*() returns an error ? #1377
Closed
@thinkerou thinkerou mentioned this pull request Jun 28, 2018
Use BindJSON multiple times fails #1078
Closed
@jeffxf jeffxf mentioned this pull request Jul 3, 2018
get request body #1295
Closed
@thinkerou thinkerou mentioned this pull request Jul 26, 2018
c *gin.Context get parameter #1439
Closed
@thinkerou thinkerou mentioned this pull request Aug 21, 2018
BindJSON returns EOF #439
Closed
toby1991 added a commit to totoval/framework that referenced this pull request Mar 6, 2019
@toby1991
let basecontroller binding could bind multiple tim
0ebd99a
gin-gonic/gin#1341
Signed-off-by: Toby Yan <[email protected]>
toby1991 added a commit to totoval/framework that referenced this pull request Mar 6, 2019
@toby1991
let basecontroller binding could bind multiple tim
d7c23f8
gin-gonic/gin#1341
Signed-off-by: Toby Yan <[email protected]>
toby1991 added a commit to totoval/framework that referenced this pull request May 10, 2019
@toby1991
let basecontroller binding could bind multiple tim
f7a8bb2
gin-gonic/gin#1341
Signed-off-by: Toby Yan <[email protected]>
toby1991 added a commit to totoval/framework that referenced this pull request May 10, 2019
@toby1991
let basecontroller binding could bind multiple tim
8573607
gin-gonic/gin#1341
Signed-off-by: Toby Yan <[email protected]>
@wulianglongrd

wulianglongrd commented Feb 24, 2023

Copy link
Copy Markdown

out of curiosity, what is the benefit of adding the ShouldBindBodyWith method instead of supporting multiple reads of the body on the ShouldBindWith method? thanks.

picone, Daemonxiao, ahmadateya, and SibNerd reacted with eyes emoji
All reactions
  • 👀 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@alitkbbl

alitkbbl commented Oct 13, 2025

Copy link
Copy Markdown

close #216

Reported problems

#216 says some formats in requests' body cannot be bound into different structs by calling multiple times.

type modelA struct {
  Foo string `form:"foo" json:"foo" binding:"required"`
  Bar int64  `form:"bar" json:"bar" binding:"required"`
}

type modelB struct {
  Hoge string `form:"hoge" json:"hoge" xml:"hoge" binding:"required"`
  Fuga int64  `form:"fuga" json:"fuga" xml:"fuga" binding:"required"`
}

func main() {
  r := gin.New()
  r.POST("/json", func(c *gin.Context) {
    fa, fb := modelA{}, modelB{}
    if aerr := c.ShouldBindWith(&fa, binding.JSON); aerr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fa})
    } else if berr := c.ShouldBindWith(&fb, binding.JSON); berr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fb})
    } else {
      c.AbortWithStatusJSON(
        http.StatusBadRequest,
        gin.H{
          "errors": gin.H{
            "modelA": aerr.Error(),
            "modelB": berr.Error(),
          },
        },
      )
    }
  })
  r.Run("0:8080")
}
# modelA can be bound successfully
$ curl -X POST -d '{"foo":"AAA","bar":123}' 0:8080/json | jq
{
  "form": {
    "foo": "AAA",
    "bar": 123
  }
}

# but modelB cannot
$ curl -X POST -d '{"hoge":"BBB","fuga":123}' 0:8080/json | jq
{
  "errors": {
    "modelA": "Key: 'modelA.Bar' Error:Field validation for 'Bar' failed on the 'req
ired' tag\nKey: 'modelA.Foo' Error:Field validation for 'Foo' failed on the 'require
' tag",
    "modelB": "EOF"
  }
}

Proposal to solve this

This PR solves this by adding a new interface binding.BindingBody & a new method c.ShouldBindBodyWith.

...
    // use ShouldBindBodyWith
    if aerr := c.ShouldBindBodyWith(&fa, binding.JSON); aerr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fa})
    } else if berr := c.ShouldBindBodyWith(&fb, binding.JSON); berr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fb})
    } else {
...
# successfully modelB bound
$ curl -X POST -d '{"hoge":"BBB","fuga":123}' 0:8080/json | jq
{
  "form": {
    "hoge": "BBB",
    "fuga": 123
  }
}

And you can mix different formats.

...
    if aerr := c.ShouldBindBodyWith(&fa, binding.JSON); aerr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fa})
    } else if berr := c.ShouldBindBodyWith(&fb, binding.XML); berr == nil {
      c.JSON(http.StatusOK, gin.H{"form": fb})
    } else {
...
$ curl -X POST -d '<?xml version="1.0" encoding="UTF-8"?>\n<root>\n<fuga>123</fuga>\n<hoge>BBB</hoge>\n</root>' 0:8080/json | jq
{
  "form": {
    "hoge": "BBB",
    "fuga": 123
  }
}

I added implementations for JSON, XML, msgpack and protobuf. Other formats, query & forms, are already available to be called multiple times, because they uses parsed req.Form (url.Values) instead of req.Body.

Question

* If you prefer to this feature, I will add unit tests.

* I'm worrying about cool naming for `bind.BindingBody`, `c.ShouldBindBodyWith`.  I'm happy if you give better names.

useful

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@thinkerou thinkerou thinkerou left review comments
@appleboy appleboy appleboy approved these changes
@javierprovecho javierprovecho Awaiting requested review from javierprovecho
@nazwa nazwa Awaiting requested review from nazwa

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

feature

Projects

None yet

Milestone

1.3

Development

Successfully merging this pull request may close these issues.

Calling bind multiple times

Uh oh!

There was an error while loading. Please reload this page.

5 participants

@delphinus @appleboy @thinkerou @wulianglongrd @alitkbbl
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.