Skip to content

Binding request body only to a map #2270

Answered by aldas
willpusher asked this question in Q&A
Discussion options

You must be logged in to vote

You can bind body like that

		if err := (&echo.DefaultBinder{}).BindBody(c, &payload); err != nil {
			return c.String(http.StatusBadRequest, "bad request")
		}

or even

	e.POST("/api/users/:uid", func(c echo.Context) error {
		var payload map[string]interface{}
		if err := json.NewDecoder(c.Request().Body).Decode(&payload); err != nil {
			return c.String(http.StatusBadRequest, "bad request")
		}

		return c.JSON(http.StatusOK, payload)
	})

and you can not bind twice as you have already consumed the request writer to the end.

In case you are using c.Bind() you can exclude path binding if you do not provide struct tag.

type User struct {
  ID string `query:"id" form:"id" json:"id" xml:"id"` 

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@willpusher
Comment options

Answer selected by willpusher
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants