2

I'm creating a API server using Go gin framework. Now I trying to add PATCH operation for /users endpoint. PATCH operation receives partial properties in json request body and updates the properties of the User model. In this case, the properties that don't appear in the json body is kept as it is.

I use ShouldBindJSON method to parse json body and it gives as as instance of PatchUserRequest struct. As properties of PatchUserRequest are pointer type, if the keys is not in the body, properties are set to nil. In other case, the property can have null value in the key. The question is that How to detect the json in request body has null value for a key or key is not given.

value of email key is null

{
  "name": "foo",
  "email": null
}

email key is not given

{
  "name": "foo"
}

The handler function and struct mapped to json is as below.

type PatchUserRequest struct {
    Name  *string   `json:"name"`
    Email *string   `json:"email"`
}

func (h *userHandler) HandleUserPatch(c *gin.Context) {
    userID := c.Param("userid")
    var json PatchUserRequest
    if err := c.ShouldBindJSON(&json); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    // Subsequent process 
}

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
toshiya
  • 183
  • 2
  • 13
  • 1
    Unmarshal into a map[string]interface{}. Ugly but the only way to distinguish these two cases (which should be treated as semantically equal). – Volker Feb 04 '21 at 07:28
  • This blog post might be a solution: https://www.calhoun.io/how-to-determine-if-a-json-key-has-been-set-to-null-or-not-provided/ – toshiya Feb 04 '21 at 08:21

0 Answers0