Binding request body only to a map #2270
-
Hi, I'm using Context#Bind to bind a JSON request body to a map (because I don't know in advance what all the fields will be). However there are a couple of path parameters, and they are also included in the map. I am currently deleting them as I need to pass the request on without introducing new fields. However this approach risks deleting valid data from the map if there are fields in the request body named the same as the path parameters. Does anyone have any suggestions of how to exclude path parameters from the bind (or conversely, how to detect if the fields exist in the request body after having already done one bind - I tried binding twice, once to the map, and secondly to a struct with fields tagged for the path parameters, but I got an EOF error message on the second bind). My version of echo is 4.7.2. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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 type User struct {
ID string `query:"id" form:"id" json:"id" xml:"id"` // <-- is missing `param:"id"` from struct tag
} |
Beta Was this translation helpful? Give feedback.
You can bind body like that
or even
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.