Reputation: 11
I have an user model like this:
type User struct {
Name string
Enabled bool // this is an bool field
Online bool // this is an bool field
// other field ...
}
when create user:
POST /api/v1/users
{
"name": "hello",
"enabled": true // option, default is true
}
the create request model is:
type CreateUserReq struct {
Name string
Enabled bool // but golang default value is false
}
when list user:
GET /api/v1/users // list all users, but golang default value is false
GET /api/v1/users?enabled=true // list enabled users
GET /api/v1/users?enabled=false // list disabled users
the list request model is:
type ListUserReq struct {
Status bool // but golang default value is false
}
What is the common way to solve this problem?
Upvotes: 1
Views: 641
Reputation: 18480
Variables without an initial value are given their zero value.
For the boolean type zero value is false
. Ref
You can use a pointer of bool
which zero value is nil
. Then you can check is Enabled
is set or not. And check in handler if Enabled
is nil
then set as true
for default case.
type CreateUserReq struct {
Name string
Enabled *bool
}
Upvotes: 2