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

c.ShouldBindBodyWith should not consume a request body #2502

Closed
momotaro98 opened this issue Sep 18, 2020 · 0 comments
Closed

c.ShouldBindBodyWith should not consume a request body #2502

momotaro98 opened this issue Sep 18, 2020 · 0 comments

Comments

@momotaro98
Copy link

  • 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
@momotaro98 momotaro98 changed the title c.ShouldBindBodyWith should not consume a request body c.ShouldBindBodyWith should not consume a request body Sep 18, 2020
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

1 participant