Echo frameworks context bind twice without losing data

Retrieve data from echo middleware, may cause you get code=400, message=EOF error.

Context.Bind only can bind once, after the request passed the middleware,the request data reader is running out, Context.Bind() function read request body data from the socket buffer, once you took it out, it just gone

that’s why it returns EOF error.

solution

    func main() {
        echoServer := echo.New()
        echoServer.POST("/api", webfunc1, middleware1)
        echoServer.Start(":8080")
    }

    func middleware1(next echo.HandlerFunc) echo.HandlerFunc {
        return func(c echo.Context) error {
            // read origin body bytes
            var bodyBytes []byte
            if c.Request().Body != nil {
                bodyBytes, _ = ioutil.ReadAll(c.Request().Body)
            }
            // write back to request body
            c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
            // parse json data
            reqData := struct {
                ID string `json:"id"`
            }{}
            err := json.Unmarshal(bodyBytes, &reqData)
            if err != nil {
                return c.JSON(400, "error json.")
            }
            fmt.Println(reqData.ID)
            return next(c)
        }
    }

    func webfunc1(c echo.Context) error {
        reqData := struct {
            Data string `json:"data"`
        }{}
        c.Bind(&reqData)
        fmt.Println(reqData.Data)
        return c.HTML(200, "200 OK.")
    }

Golang: Read from an io.ReadWriter without losing its content

Leave a Reply

Your email address will not be published. Required fields are marked *