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

Comment From: jiaopengzi

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

Comment From: VarusHsu

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.

Comment From: VarusHsu

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