Skip to content

Cannot read request body after ctx.Bind #2681

Open
@hayashikun

Description

@hayashikun

Issue Description

I want to get the request body in httpErrorHandler, but I can't.
Once a request body is read by ctx.Bind, it cannot be read afterward.

To read again after reading, the ReaderCloser must be set, but DefaultBinder#BindBody does not do this.

c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody)) // Reset

What is the best way to do this?

Checklist

  • Dependencies installed
  • No typos
  • Searched existing issues and docs

Expected behavior

Can read the request body after ctx.Bind or in httpErrorHandler

Actual behavior

Cannot read the request body after ctx.Bind

Steps to reproduce

Working code to debug

body1 := ctx.Request().Body
buf1, err := io.ReadAll(body1)
if err == nil {
	println("before: " + string(buf1))
}
ctx.Request().Body = io.NopCloser(bytes.NewBuffer(buf1))

bindErr := ctx.Bind(req)

body2 := ctx.Request().Body
buf2, err := io.ReadAll(body2)
if err == nil {
	println("after: " + string(buf2))
}
ctx.Request().Body = io.NopCloser(bytes.NewBuffer(buf2))

return bindErr

When a POST request is sent with {"aaa": "hoge"}, the following log is output

before: {"aaa": "hoge"}
after:

Version/commit

v4.12.0

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