So, I'm making a rest api that handles JSON data. However I have yet to found an option that makes a specific value (lets say the ip of the sender) required. So if no IP is received from the sender it will just return an error. Any help would be appreciated.
评论:
BS_in_BS:
JonTargaryanTheFirst:you'd have to go into more detail about what packages/frameworks you're using.
One way to do it could be to use tag on struct fields with some reflection.
BS_in_BS:Ok. The main packages I'm using "gorilla/mux" and "strconv". So basically I have a Route struct which fetches Ip, Id, Time etc. (currently only works with postman injection). And I would like it to return an error if the Ip field is omitted empty. I'm thinking something like this: if { int.Ip == nil (panic "Ip field required)}.
koalefant:the quickest way is to instead of a
panic
call, use http.Error and return a 400 response with your error message.
Implement the json Unmarshaler interface, it’s something like UnmarshalJSON(b []byte) error
If ip is not there just return an error
You can even do verifications on it to make sure it’s within a certain range or that it’s valid syntax
