skip to Main Content

I have API which accepts PATCH method and updates given fields.
PATCH request with below body changes age of User.

{
   "age": 10
}

I had problem on treating null value.
My User struct as below:

type User struct {
    Name string
    Age int
    Schedule *schedule
}

type Schedule struct {
    time int
    weekdays []int
}

To remove schedule field on user, request body should be like:

{
    "schedule": null
}

Then, I have to identify whether null value is given or not provided anything, which is not possible with above definition.
I wrote new struct that helps identifying it (https://www.calhoun.io/how-to-determine-if-a-json-key-has-been-set-to-null-or-not-provided/):

type User struct {
    Name 
    Age int
    Schedule Optional[Schedule]
}

type Optional[T any] struct {
    Value   *T
    Defined bool
}

func (t *Optional[T]) UnmarshalJSON(data []byte) error {
    t.Defined = true
    return json.Unmarshal(data, &t.Value)
}

func (t *Optional[T]) IsNullDefined() bool {
    return t.Defined && t.Value == nil
}

func (t *Optional[T]) HasValue() bool {
    return t.Defined && t.Value != nil
}

And, now I have problem that actions are different between

{
    "age": null
}

which will be ignored and

{
    "schedule": null
}

which will remove the schedule.

How can I handle and prevent null value for other type, which should be type error?


Edit:

In one sentence, I want to reject all null value given field (not a non-provided) except Optional struct. You can suggest me any other solution that solves the problem.

2

Answers


  1. Chosen as BEST ANSWER

    Found a solution from @Volker and post self answer:

    The above question uses Merge Patch JSON (rfc7396). There's a library for it.

    https://pkg.go.dev/github.com/evanphx/json-patch/v5#MergePatch

    I pull GET result and merge GET result and json patch body. Then, you can notice which values are nullified.


  2. Try making the Age a *int type.

    Try making the Age an Optional[int] type. https://go.dev/play/p/f56pdESOEt7

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search