Skip to content

c.ShouldBindBodyWith should not consume a request body #2502

@momotaro98

Description

@momotaro98
  • With issues:
    • Use the search tool before opening a new issue.
    • Please provide source code and commit sha if you found a bug.
    • Review existing issues and provide feedback or react to them.

Description

This issue is related to #439, #1810.

I think c.ShouldBindBodyWith should not consume a request body for next binding.

When I read the current README doc about this method, I thought it doesn't but it does so I've got an EOF error like the example below.

I think it's now confusing for users.

Thanks.

How to reproduce

package main

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type MyStruct struct {
	Key string `json:"key" binding:"required"`
}

func MyMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var h MyStruct

		if err := c.ShouldBindBodyWith(&h, binding.JSON); err != nil {
			c.JSON(400, gin.H{
				"message": fmt.Sprintf("%+v", err),
			})
			return
		}

		c.Next()
	}
}

func main() {
	r := gin.Default()
	r.Use(MyMiddleware())
	r.POST("/post", func(c *gin.Context) {
		var h MyStruct

		decoder := json.NewDecoder(c.Request.Body)
		err := decoder.Decode(&h)
		if err != nil {
				c.JSON(400, gin.H{
					"message": fmt.Sprintf("%+v", err),
				})
				return
		}

		c.JSON(200, gin.H{
			"message": "ok",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Expectations

$ curl --location --request POST 'http://localhost:8080/post' \
--header 'Content-Type: application/json' \
--data-raw '{
    "key": "value"
}'
{"message":"ok"}

Actual result

$ curl --location --request POST 'http://localhost:8080/post' \
--header 'Content-Type: application/json' \
--data-raw '{
    "key": "value"
}'
{"message":"EOF"}

Environment

  • go version: go1.15 darwin/amd64
  • gin version (or commit ref): 3100b7c
  • operating system: darwin/amd64

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions