Skip to content

Binding confusion when params and request body have the same named field #1423

Closed
@waterandair

Description

@waterandair

Issue Description

in this PR #1165 added feature to map url params to a struct with the default binder, now if the url params and request body have same named field but different variable type, the default binder will throw an type parse error.

Checklist

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

Expected behaviour

Maybe binder should bind url params just when struct really contains params tag.

Actual behaviour

If struct have a field named id with json tag, and the url have a param named id, the default binder will throw an error

Steps to reproduce

  1. run this code with echo v4
func main() {
	app := echo.New()

	app.POST("/user/:id", handler)
	app.Logger.Fatal(app.Start(":1323"))
}

type Body struct {
	ID   uint64 `json:"id"`
	Type string `json:"type"`
}

func handler(ctx echo.Context) error {
	id := ctx.Param("id")
	doSomething(id)

	body := new(Body)
	if err := ctx.Bind(body); err != nil {
		return ctx.JSON(http.StatusInternalServerError, err)
	}

	return ctx.JSON(http.StatusOK, body)
}

func doSomething(id string) {
}
  1. use curl make a request
$ curl -H "Content-type: application/json" -X POST -d '{"id":1,"type":"any"}' http://localhost:1323/user/a
  {"message":"strconv.ParseUint: parsing \"a\": invalid syntax"}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions