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

ctx.shouldBindJSON crashes when called twice #4110

Open
simon-winter opened this issue Dec 2, 2024 · 3 comments
Open

ctx.shouldBindJSON crashes when called twice #4110

simon-winter opened this issue Dec 2, 2024 · 3 comments

Comments

@simon-winter
Copy link

Description

When having a layered architecture that goes through some middleware before reaching the default route, than calling ShouldBindJSON a second time on the same context will fatal crash the app with EOF exception.

How to reproduce

call this twice with a valid model/JSON in a HandlerFunc:

if err := ctx.ShouldBindJSON(model); err != nil {
	ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	return
}

Expectations

I can bind the json multiple times to an object

Actual result

some internal reader goes EOF when calling it a second time

Environment

  • go version: 1.23.3
  • gin version (or commit ref): 1.10.0
  • operating system: Windows
@jiaopengzi
Copy link

Yes, I have the same need and am also encountering the EOF issue. Looking forward to a resolution.

@VarusHsu
Copy link

VarusHsu commented Dec 3, 2024

The request body is an io.Reader instance, which typically contains a byte buffer and a read offset. When ShouldBindJSON is called for the first time, it reads the buffer and sets the offset to the end.

@VarusHsu
Copy link

VarusHsu commented Dec 3, 2024

You can read it only once and store it in the gin.Context to pass between middleware. I hope my answer helps you. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants