Repository navigation
How can I tell if something was submitted as zero value or omitted from the request body? #2466
Replies: 2 comments
|
Use a pointer for each optional scalar field, and bind into a fresh request struct: type PatchRequest struct {
Count *int `json:"count"`
}
var requestData PatchRequest
if err := (&echo.DefaultBinder{}).BindBody(c, &requestData); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid-data").SetInternal(err)
}
updates := map[string]any{}
if requestData.Count != nil {
updates["count"] = *requestData.Count
}Then pass only the fields in I checked this through Echo v4.15.4's
This distinguishes omission from an explicit scalar value. If your PATCH contract also distinguishes The pointer behavior comes from encoding/json.Unmarshal. |
|
Using a pointer is the usual fix, and the reply above covers it well. One thing worth adding: type PatchRequest struct {
Count json.RawMessage `json:"count"`
}After binding, If you do not care about null, stick with the pointer version. It is simpler and covers most PATCH endpoints. |
Uh oh!
There was an error while loading. Please reload this page.
I am currently writing a PATCH endpoint with Go Echo using Go Playground for validation. I use the method below to bind my JSON request body to a struct. The issue is that this is a patch endpoint, so properties are optional in the request body JSON. How can I determine if the request body submitted a property as its zero value or was omitted? Because when I look at the struct, I get the zero value even if the field was omitted from the JSON request body.
For example, let's say I have a property called "count." This is a PATCH endpoint, so the count could be omitted completely or submitted with an integer. If I use Go Echo's bind capabilities, the bound struct will show the "count = 0" (the zero value equivalent) if it is omitted. But it wasn't submitted, so I should leave the value untouched and not update it to "0". If the request contains "count: 0", I should update it.
How would I know if "count" was submitted? I hope I don't have to compare every property to the existing database values to see if it changed before saving.
All reactions