Let's say I have the following Go structure on the server
type account struct { Name string Balance int }
I want to call json.Decode for an incoming request to parse it in my account.
var ac account err := json.NewDecoder(r.Body).Decode(&ac)
If the client sends the following request:
{ "name": " test@example.com ", "balance": "3" }
Decode () will return the following error:
json: cannot unmarshal string into Go value of type int
Now you can parse this back to "you sent the line for" Balance ", but you really had to send an integer," but it's complicated because you don't know the name of the field. It also becomes much more complicated if you have many fields in the query - you do not know which one could not be parsed.
What is the best way to accept this incoming request in Go and return the "Balance must be a string" error message for any arbitrary number of integer fields in the request?
source share