Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle patch request with unset value in golang

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:

  1. using pointer to deal with null problem

    type User struct {
        Name *string
    }
    
  2. using nullable library

    type User struct {
        Name  sql.NullString
    }
    
  3. 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.

like image 205
sunny tam Avatar asked Dec 03 '22 11:12

sunny tam


1 Answers

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.

like image 123
Adrian Avatar answered Dec 25 '22 14:12

Adrian