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

Cannot bind twice http request (JSON format) #1844

Open
sebd71 opened this issue Nov 21, 2019 · 1 comment
Open

Cannot bind twice http request (JSON format) #1844

sebd71 opened this issue Nov 21, 2019 · 1 comment

Comments

@sebd71
Copy link

@sebd71 sebd71 commented Nov 21, 2019

Description

Call multiples time c.Bind with "application/json" or "application/xml" binder type is not working due to the fact that req.body can only be read one time.

Steps to Reproduce the Problem

Following test illustrates the problem :

package binding_test

import (
	"encoding/json"
	"net/http"
	"testing"

	"github.com/gobuffalo/buffalo"
	"github.com/gobuffalo/buffalo/render"
	"github.com/gobuffalo/httptest"
	"github.com/stretchr/testify/require"
)

func Test_BindTwiceJSON(t *testing.T) {
	r := require.New(t)

	render := render.New(render.Options{
		DefaultContentType: "application/json",
	})

	type U struct {
		F string
	}
	app := buffalo.New(buffalo.Options{})
	app.POST("/", func(c buffalo.Context) error {
		var ux, uy U
		// Bind once
		if err := c.Bind(&ux); err != nil {
			return c.Render(http.StatusInternalServerError, render.String(err.Error()))
		}
		// Bind twice
		if err := c.Bind(&uy); err != nil {
			return c.Render(http.StatusInternalServerError, render.String(err.Error()))
		}
		return c.Render(http.StatusOK, render.JSON(U{
			F: "ux=" + ux.F + ", uy=" + uy.F + " OK",
		}))
	})

	w := httptest.New(app)
	res := w.JSON("/").Post(&U{F: "foo"})

	r.Equal(http.StatusOK, res.Code, "Http code not OK, body='%v'", res.Body)

	var resVal U
	r.NoError(json.Unmarshal(res.Body.Bytes(), &resVal))
	r.Equal("ux=foo, uy=foo OK", resVal.F)
}

Just create a new file (for example: binding/binding_bind_json_test.go) in buffalo repo and run tests (make test -m Test_BindTwiceJSON)
You will get the following error :

--- FAIL: Test_BindTwiceJSON (0.07s)
    binding_bind_json_test.go:43: 
                Error Trace:    binding_bind_json_test.go:43
                Error:          Not equal: 
                                expected: 200
                                actual  : 500
                Test:           Test_BindTwiceJSON
                Messages:       Http code not OK, body='EOF'

I will post soon a fix proposal based on packd.
My fix is very similar to what you've done in #1480.

@sebd71

This comment has been minimized.

Copy link
Author

@sebd71 sebd71 commented Nov 21, 2019

Pull request posted : #1846

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant
You can’t perform that action at this time.