I am working on a patch restful request that the body json contain some omitted value while sending to golang. Since an unset value will lead the golang struct become default value. So I would like to know if there are any solution to deal with patch request omit data?
As I know, a basic type like string / int cannot be nullable in golang. there are different approach to deal with unset value patch request. For example:
using pointer to deal with null problem
type User struct {
Name *string
}
using nullable library
type User struct {
Name sql.NullString
}
using map[string][]interface{}
to see if the value is set
Is there any better solution to deal with nullable value inside struct? since this 3 should be work around to deal with the nullable value.
If you're using PATCH
in a RESTful way, that means it's updating some existing data, and only overwriting those fields included in the request body. Which means you don't actually need to know which fields are set or not; you can just load your canonical object and unmarshal over it to replace any fields that are found in the JSON, while leaving any others untouched:
canonObj := getObjectFromDBOrSomething()
err := json.NewDecoder(req.Body).Decode(canonObj)
This will overwrite any fields in canonObj
with fields from the request, but any fields not in the request won't be touched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With