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
}