#runtime error: invalid memory address or nil pointer dereference

13 messages · Page 1 of 1 (latest)

regal lava
#

posting a form to my golang backend where the birthdate value is null gives me that error above. the field is of type *time.Time. I also check if the value is nil...




    var birthdatePtr *time.Time
    if req.Birthdate != nil {
        birthdateUTC := req.Birthdate.UTC()
        birthdatePtr = &birthdateUTC
    }

    employee := models.Employee{
        UserId:    createdUser.Id,
        Email:     req.Email,
        Firstname: req.Firstname,
        Lastname:  req.Lastname,
        Birthdate: birthdatePtr,
        Phone:     req.Phone,
        IsActive:  req.IsActive,
        IsDeleted: false,
        EmpTypeId: req.EmployeeTypeId,
        CompanyId: companyId,
    }

    createdEmployee, err := s.employeeRepo.CreateEmployee(tx, &employee)```

how can i make it possible that the client sends an null birthdate to the backend? if i enter a date in the form, it works
naive heart
#

Can post the req struct

regal lava
# naive heart Can post the req struct

type CreateEmployeeRequest struct {
Email string json:"email"
Firstname string json:"firstname"
Lastname string json:"lastname"
Birthdate *time.Time json:"birthdate"
Phone *string json:"phone"
IsActive bool json:"isActive"
EmployeeTypeId uuid.UUID json:"employeeTypeId"
ImageUrl *string json:"imageUrl"
CfValues map[string]string json:"cfValues"
Role sharedModels.RoleName json:"role"
Timezone string json:"Timezone"
Language string json:"language"
}

naive heart
#

Are you using any validator?

regal lava
#

only on client side. i use zod to make sure that the user either chooses a date or leaves it empty which sets the initialvalue to null

#

before i did the utc part here it worked just fine but since i do the utc part it is broken for null values

naive heart
#

When you are getting the value from the req treat it as a string and then parse the time

#

Also you could use a validator

rose seal
#

When you get an error like this it's important to use the information available in the stack trace. See this post: #go-chat message

regal lava
naive heart
#

Use debug.Stack() to get an in detail stack list

rose seal
#

Okay, so you're recovering. If you're debugging you may as well get rid of the recovery and let it crash completely. Or do what karthaj said.

regal lava
#

i reverted it back to how it was and it still did not work.. i quit air, removed .app and used zsh instead of tmux and it worked....wasted an hour for nothing again