Invalid Memory Address or Nil Pointer Deference Issue in Gin-Gonic

233 Views Asked by At

Revised Question

I am trying to create a new user using Golang. I have a CreateUser() function in my UserImplementation struct which takes a pointer to a User model. The function is responsible for creating a new user record in the database. However, when I try to run the function, I keep getting the error message "Nil pointer". Can someone help me figure out what I'm doing wrong?

Here is the code for my CreateUser() function:

func (usr *UserImplementation) CreateUser(user *models.User) (*models.User, error) {

    fmt.Println("User date", user.CreatedAt)
    fmt.Println("User name", user.FirstName)
    fmt.Println("User data", user.Password)

    pg := databaseapi.NewApiConfig{}

    params := database_utils.CreateUserParams{
        ID:           uuid.New(),
        CreatedAt:    time.Now().UTC(),
        UpdatedAt:    time.Now().UTC(),
        FirstName:    user.FirstName,
        LastName:     user.LastName,
        OtherName:    user.OtherName,
        Password:     user.Password,
        Email:        user.Email,
        ProfileImage: user.ProfileImage,
        Status:       user.Status,
        Username:     user.Username,
        IsAdmin:      user.IsAdmin,
        Role:         user.Role,
        Gender:       user.Gender,
        PhoneNumber:  user.PhoneNumber,
    }

    userResponse, err := pg.ApiConfig.DB.CreateUser(usr.ctx, params)

    if err != nil {
        return nil, fmt.Errorf("error: %v", err.Error())
    }
    return (*models.User)(&userResponse), nil

}

I also have a UserController struct that has a CreateUser() function. Here is the code for that:

type UserController struct {
    UserCtrl *usersimpl.UserImplementation
}

func (usrCtrl *UserController) CreateUser(ctx *gin.Context) {
    var user models.User
    
    if err := ctx.ShouldBindJSON(&user); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "Error": err.Error(),
        })
        return
    }
    
    _, err := utilities.EmailValidator(user.Email)
    
    if err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "Error": err.Error(),
        })
        return
    }

    hashPassword, err := utilities.HashPassword(user.Password)
    
    if err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "Error": err.Error(),
        })
    }

    user.Password = hashPassword
    
    resp, err := usrCtrl.UserCtrl.CreateUser(&user)
    
    if err != nil {
        ctx.JSON(
            http.StatusBadRequest,
            gin.H{
                "Error": err.Error(),
            },
        )
        return
    }

    ctx.JSON(http.StatusOK, gin.H{
        "response": resp,
    })

}

I've also created a UserImplementation struct which has a NewUserService() function. Here is the code for that:

type UserImplementation struct {
    pg  *database_utils.Queries
    ctx context.Context
}

func NewUserService(pg *database_utils.Queries, ctx context.Context) *UserImplementation {
    return &UserImplementation{
        pg:  pg,
        ctx: ctx,
    }
}
1

There are 1 best solutions below

1
On

It is hard to say because you have provided only part of code. I think there can be two potential issues:

  1. "user" structure that passed as a parameter to the method CreateUser has field(-s) that has a pointer data type and they has nil value(-s)
  2. other issues can be related to pg.ApiConfig.DB.CreateUser and/or it's returned value

There are at least two ways to find the issue:

  1. check line 44 (where you got a panic)
  2. use debugger and check all needable values are not nil as well as inspect pg.ApiConfig.DB.CreateUser deeply

Hope it helps you to localise issue and find solution