Home > Back-end >  Go - JSON validation throwing error unless I use pointer in the struct. Why?
Go - JSON validation throwing error unless I use pointer in the struct. Why?

Time:07-22

Here is my validation structure:

type PostEmail struct {
    Username       string `json:"username" validate:"required"`
    Email          string `json:"email" validate:"required"`
    IsRefreshEmail *bool  `json:"isRefreshEmail" validate:"required"`
}

I'm pointing the value of IsRefreshEmail with *bool. If I remove the pointer and I try to call my API without it, the API will throw a bad syntax error. That will happen only if the boolean value will be false. If it's true even if you remove the pointer the API will respond correctly.

Why is this happening? It's normal? I can't understand it and i don't even know if I'm doing it wrong with the pointer. What I surely know is that if I remove the * from bool and I insert false as value in postman for the field isRefreshEmail the API will throw an exception.

Someone can explain please? Thank you.

CodePudding user response:

A boolean can represent two values, false or true:

var IsRefreshEmail bool

A boolean pointer can represent three values, false, true or nil:

var IsRefreshEmail *bool

The benefit of this, is that you can compare false with nil:

{"email": "hello", "isRefreshEmail": false}
{"email": "hello"}

without the pointer, the two JSON above will be identical after Unmarshal. Depending on your situation, you might not care about that. However if you need to know if the value was omitted, then pointer is required.

CodePudding user response:

Default value of bool is false

Default value of *bool is nil

So when using with pointer and the value you send is false -> fasle

But when use with bool -> you send false -> validate with check and make it failure validation(same as default value)

The problem is same for int and *int with the 0 value

  • Related